| 1 |
// Copyright 2018 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
// Package gcppubsub provides a pubsub implementation that uses GCP |
| 16 |
// PubSub. Use OpenTopic to construct a *pubsub.Topic, and/or OpenSubscription |
| 17 |
// to construct a *pubsub.Subscription. |
| 18 |
// |
| 19 |
// # URLs |
| 20 |
// |
| 21 |
// For pubsub.OpenTopic and pubsub.OpenSubscription, gcppubsub registers |
| 22 |
// for the scheme "gcppubsub". |
| 23 |
// The default URL opener will creating a connection using use default |
| 24 |
// credentials from the environment, as described in |
| 25 |
// https://cloud.google.com/docs/authentication/production. |
| 26 |
// To customize the URL opener, or for more details on the URL format, |
| 27 |
// see URLOpener. |
| 28 |
// See https://gocloud.dev/concepts/urls/ for background information. |
| 29 |
// |
| 30 |
// GCP Pub/Sub emulator is supported as per https://cloud.google.com/pubsub/docs/emulator |
| 31 |
// So, when environment variable 'PUBSUB_EMULATOR_HOST' is set |
| 32 |
// driver connects to the specified emulator host by default. |
| 33 |
// |
| 34 |
// # Message Delivery Semantics |
| 35 |
// |
| 36 |
// GCP Pub/Sub supports at-least-once semantics; applications must |
| 37 |
// call Message.Ack after processing a message, or it will be redelivered. |
| 38 |
// See https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery |
| 39 |
// for more background. |
| 40 |
// |
| 41 |
// # As |
| 42 |
// |
| 43 |
// gcppubsub exposes the following types for As: |
| 44 |
// - Topic: *raw.PublisherClient |
| 45 |
// - Subscription: *raw.SubscriberClient |
| 46 |
// - Message.BeforeSend: *pb.PubsubMessage |
| 47 |
// - Message.AfterSend: *string for the pb.PublishResponse.MessageIds entry corresponding to the message. |
| 48 |
// - Message: *pb.PubsubMessage, *pb.ReceivedMessage |
| 49 |
// - Error: *google.golang.org/grpc/status.Status |
| 50 |
package gcppubsub // import "gocloud.dev/pubsub/gcppubsub" |
| 51 |
|
| 52 |
import ( |
| 53 |
"context" |
| 54 |
"fmt" |
| 55 |
"net/url" |
| 56 |
"os" |
| 57 |
"path" |
| 58 |
"regexp" |
| 59 |
"strconv" |
| 60 |
"strings" |
| 61 |
"sync" |
| 62 |
"time" |
| 63 |
|
| 64 |
raw "cloud.google.com/go/pubsub/apiv1" |
| 65 |
pb "cloud.google.com/go/pubsub/apiv1/pubsubpb" |
| 66 |
"github.com/google/wire" |
| 67 |
"gocloud.dev/gcerrors" |
| 68 |
"gocloud.dev/gcp" |
| 69 |
"gocloud.dev/internal/gcerr" |
| 70 |
"gocloud.dev/internal/useragent" |
| 71 |
"gocloud.dev/pubsub" |
| 72 |
"gocloud.dev/pubsub/batcher" |
| 73 |
"gocloud.dev/pubsub/driver" |
| 74 |
"google.golang.org/api/option" |
| 75 |
"google.golang.org/grpc" |
| 76 |
"google.golang.org/grpc/credentials" |
| 77 |
"google.golang.org/grpc/credentials/insecure" |
| 78 |
"google.golang.org/grpc/credentials/oauth" |
| 79 |
"google.golang.org/grpc/status" |
| 80 |
) |
| 81 |
|
| 82 |
var endPoint = "pubsub.googleapis.com:443" |
| 83 |
|
| 84 |
var sendBatcherOpts = &batcher.Options{ |
| 85 |
MaxBatchSize: 1000, // The PubSub service limits the number of messages in a single Publish RPC |
| 86 |
MaxHandlers: 2, |
| 87 |
// The PubSub service limits the size of the request body in a single Publish RPC. |
| 88 |
// The limit is currently documented as "10MB (total size)" and "10MB (data field)" per message. |
| 89 |
// We are enforcing 9MiB to give ourselves some headroom for message attributes since those |
| 90 |
// are currently not considered when computing the byte size of a message. |
| 91 |
MaxBatchByteSize: 9 * 1024 * 1024, |
| 92 |
} |
| 93 |
|
| 94 |
var defaultRecvBatcherOpts = &batcher.Options{ |
| 95 |
// GCP Pub/Sub returns at most 1000 messages per RPC. |
| 96 |
MaxBatchSize: 1000, |
| 97 |
MaxHandlers: 10, |
| 98 |
} |
| 99 |
|
| 100 |
var ackBatcherOpts = &batcher.Options{ |
| 101 |
// The PubSub service limits the size of Acknowledge/ModifyAckDeadline RPCs. |
| 102 |
// (E.g., "Request payload size exceeds the limit: 524288 bytes."). |
| 103 |
MaxBatchSize: 1000, |
| 104 |
MaxHandlers: 2, |
| 105 |
} |
| 106 |
|
| 107 |
func init() { |
| 108 |
o := new(lazyCredsOpener) |
| 109 |
pubsub.DefaultURLMux().RegisterTopic(Scheme, o) |
| 110 |
pubsub.DefaultURLMux().RegisterSubscription(Scheme, o) |
| 111 |
} |
| 112 |
|
| 113 |
// Set holds Wire providers for this package. |
| 114 |
var Set = wire.NewSet( |
| 115 |
Dial, |
| 116 |
PublisherClient, |
| 117 |
SubscriberClient, |
| 118 |
wire.Struct(new(SubscriptionOptions)), |
| 119 |
wire.Struct(new(TopicOptions)), |
| 120 |
wire.Struct(new(URLOpener), "Conn", "TopicOptions", "SubscriptionOptions"), |
| 121 |
) |
| 122 |
|
| 123 |
// lazyCredsOpener obtains Application Default Credentials on the first call |
| 124 |
// to OpenTopicURL/OpenSubscriptionURL. |
| 125 |
type lazyCredsOpener struct { |
| 126 |
init sync.Once |
| 127 |
opener *URLOpener |
| 128 |
err error |
| 129 |
} |
| 130 |
|
| 131 |
func (o *lazyCredsOpener) defaultConn(ctx context.Context) (*URLOpener, error) { |
| 132 |
o.init.Do(func() { |
| 133 |
var conn *grpc.ClientConn |
| 134 |
var err error |
| 135 |
if e := os.Getenv("PUBSUB_EMULATOR_HOST"); e != "" { |
| 136 |
// Connect to the GCP pubsub emulator by overriding the default endpoint |
| 137 |
// if the 'PUBSUB_EMULATOR_HOST' environment variable is set. |
| 138 |
// Check https://cloud.google.com/pubsub/docs/emulator for more info. |
| 139 |
endPoint = e |
| 140 |
conn, err = dialEmulator(ctx, e) |
| 141 |
if err != nil { |
| 142 |
o.err = err |
| 143 |
return |
| 144 |
} |
| 145 |
} else { |
| 146 |
creds, err := gcp.DefaultCredentials(ctx) |
| 147 |
if err != nil { |
| 148 |
o.err = err |
| 149 |
return |
| 150 |
} |
| 151 |
|
| 152 |
conn, _, err = Dial(ctx, creds.TokenSource) |
| 153 |
if err != nil { |
| 154 |
o.err = err |
| 155 |
return |
| 156 |
} |
| 157 |
} |
| 158 |
o.opener = &URLOpener{Conn: conn} |
| 159 |
}) |
| 160 |
return o.opener, o.err |
| 161 |
} |
| 162 |
|
| 163 |
func (o *lazyCredsOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 164 |
opener, err := o.defaultConn(ctx) |
| 165 |
if err != nil { |
| 166 |
return nil, fmt.Errorf("open topic %v: failed to open default connection: %v", u, err) |
| 167 |
} |
| 168 |
return opener.OpenTopicURL(ctx, u) |
| 169 |
} |
| 170 |
|
| 171 |
func (o *lazyCredsOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 172 |
opener, err := o.defaultConn(ctx) |
| 173 |
if err != nil { |
| 174 |
return nil, fmt.Errorf("open subscription %v: failed to open default connection: %v", u, err) |
| 175 |
} |
| 176 |
return opener.OpenSubscriptionURL(ctx, u) |
| 177 |
} |
| 178 |
|
| 179 |
// Scheme is the URL scheme gcppubsub registers its URLOpeners under on pubsub.DefaultMux. |
| 180 |
const Scheme = "gcppubsub" |
| 181 |
|
| 182 |
// URLOpener opens GCP Pub/Sub URLs like "gcppubsub://projects/myproject/topics/mytopic" for |
| 183 |
// topics or "gcppubsub://projects/myproject/subscriptions/mysub" for subscriptions. |
| 184 |
// |
| 185 |
// The shortened forms "gcppubsub://myproject/mytopic" for topics or |
| 186 |
// "gcppubsub://myproject/mysub" for subscriptions are also supported. |
| 187 |
// |
| 188 |
// The following query parameters are supported: |
| 189 |
// |
| 190 |
// - max_recv_batch_size: sets SubscriptionOptions.MaxBatchSize. |
| 191 |
// - max_send_batch_size: sets TopicOptions.BatcherOptions.MaxBatchSize. |
| 192 |
// - nacklazy: sets SubscriberOptions.NackLazy. The value must be parseable by `strconv.ParseBool`. |
| 193 |
// |
| 194 |
// Currently their use is limited to subscribers. |
| 195 |
type URLOpener struct { |
| 196 |
// Conn must be set to a non-nil ClientConn authenticated with |
| 197 |
// Cloud Pub/Sub scope or equivalent. |
| 198 |
Conn *grpc.ClientConn |
| 199 |
|
| 200 |
// TopicOptions specifies the options to pass to OpenTopic. |
| 201 |
TopicOptions TopicOptions |
| 202 |
// SubscriptionOptions specifies the options to pass to OpenSubscription. |
| 203 |
SubscriptionOptions SubscriptionOptions |
| 204 |
} |
| 205 |
|
| 206 |
// OpenTopicURL opens a pubsub.Topic based on u. |
| 207 |
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 208 |
opts := o.TopicOptions |
| 209 |
|
| 210 |
for param, value := range u.Query() { |
| 211 |
switch param { |
| 212 |
case "max_send_batch_size": |
| 213 |
maxBatchSize, err := queryParameterInt(value) |
| 214 |
if err != nil { |
| 215 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q: %v", u, param, err) |
| 216 |
} |
| 217 |
|
| 218 |
if maxBatchSize <= 0 || maxBatchSize > 1000 { |
| 219 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q: must be between 1 and 1000", u, param) |
| 220 |
} |
| 221 |
|
| 222 |
opts.BatcherOptions.MaxBatchSize = maxBatchSize |
| 223 |
default: |
| 224 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 225 |
} |
| 226 |
} |
| 227 |
pc, err := PublisherClient(ctx, o.Conn) |
| 228 |
if err != nil { |
| 229 |
return nil, err |
| 230 |
} |
| 231 |
topicPath := path.Join(u.Host, u.Path) |
| 232 |
if topicPathRE.MatchString(topicPath) { |
| 233 |
return OpenTopicByPath(pc, topicPath, &opts) |
| 234 |
} |
| 235 |
// Shortened form? |
| 236 |
topicName := strings.TrimPrefix(u.Path, "/") |
| 237 |
return OpenTopic(pc, gcp.ProjectID(u.Host), topicName, &opts), nil |
| 238 |
} |
| 239 |
|
| 240 |
// OpenSubscriptionURL opens a pubsub.Subscription based on u. |
| 241 |
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 242 |
// Set subscription options to use defaults |
| 243 |
opts := o.SubscriptionOptions |
| 244 |
|
| 245 |
for param, value := range u.Query() { |
| 246 |
switch param { |
| 247 |
case "max_recv_batch_size": |
| 248 |
maxBatchSize, err := queryParameterInt(value) |
| 249 |
if err != nil { |
| 250 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: %v", u, param, err) |
| 251 |
} |
| 252 |
|
| 253 |
if maxBatchSize <= 0 || maxBatchSize > 1000 { |
| 254 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: must be between 1 and 1000", u, param) |
| 255 |
} |
| 256 |
|
| 257 |
opts.MaxBatchSize = maxBatchSize |
| 258 |
case "nacklazy": |
| 259 |
var err error |
| 260 |
nackLazy, err := queryParameterBool(value) |
| 261 |
if err != nil { |
| 262 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: %v", u, param, err) |
| 263 |
} |
| 264 |
opts.NackLazy = nackLazy |
| 265 |
default: |
| 266 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 267 |
} |
| 268 |
} |
| 269 |
sc, err := SubscriberClient(ctx, o.Conn) |
| 270 |
if err != nil { |
| 271 |
return nil, err |
| 272 |
} |
| 273 |
subPath := path.Join(u.Host, u.Path) |
| 274 |
if subscriptionPathRE.MatchString(subPath) { |
| 275 |
return OpenSubscriptionByPath(sc, subPath, &opts) |
| 276 |
} |
| 277 |
// Shortened form? |
| 278 |
subName := strings.TrimPrefix(u.Path, "/") |
| 279 |
return OpenSubscription(sc, gcp.ProjectID(u.Host), subName, &opts), nil |
| 280 |
} |
| 281 |
|
| 282 |
type topic struct { |
| 283 |
path string |
| 284 |
client *raw.PublisherClient |
| 285 |
} |
| 286 |
|
| 287 |
// Dial opens a gRPC connection to the GCP Pub Sub API. |
| 288 |
// |
| 289 |
// The second return value is a function that can be called to clean up |
| 290 |
// the connection opened by Dial. |
| 291 |
func Dial(ctx context.Context, ts gcp.TokenSource) (*grpc.ClientConn, func(), error) { |
| 292 |
conn, err := grpc.DialContext(ctx, endPoint, |
| 293 |
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), |
| 294 |
grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: ts}), |
| 295 |
// The default message size limit for gRPC is 4MB, while GCP |
| 296 |
// PubSub supports messages up to 10MB. Aside from the message itself |
| 297 |
// there is also other data in the gRPC response, bringing the maximum |
| 298 |
// response size above 10MB. Tell gRPC to support up to 11MB. |
| 299 |
// https://github.com/googleapis/google-cloud-node/issues/1991 |
| 300 |
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*11)), |
| 301 |
useragent.GRPCDialOption("pubsub"), |
| 302 |
) |
| 303 |
if err != nil { |
| 304 |
return nil, nil, err |
| 305 |
} |
| 306 |
return conn, func() { conn.Close() }, nil |
| 307 |
} |
| 308 |
|
| 309 |
// dialEmulator opens a gRPC connection to the GCP Pub Sub API. |
| 310 |
func dialEmulator(ctx context.Context, e string) (*grpc.ClientConn, error) { |
| 311 |
conn, err := grpc.DialContext(ctx, e, |
| 312 |
grpc.WithTransportCredentials(insecure.NewCredentials()), |
| 313 |
useragent.GRPCDialOption("pubsub")) |
| 314 |
if err != nil { |
| 315 |
return nil, err |
| 316 |
} |
| 317 |
return conn, nil |
| 318 |
} |
| 319 |
|
| 320 |
// PublisherClient returns a *raw.PublisherClient that can be used in OpenTopic. |
| 321 |
func PublisherClient(ctx context.Context, conn *grpc.ClientConn) (*raw.PublisherClient, error) { |
| 322 |
return raw.NewPublisherClient(ctx, option.WithGRPCConn(conn)) |
| 323 |
} |
| 324 |
|
| 325 |
// SubscriberClient returns a *raw.SubscriberClient that can be used in OpenSubscription. |
| 326 |
func SubscriberClient(ctx context.Context, conn *grpc.ClientConn) (*raw.SubscriberClient, error) { |
| 327 |
return raw.NewSubscriberClient(ctx, option.WithGRPCConn(conn)) |
| 328 |
} |
| 329 |
|
| 330 |
// TopicOptions will contain configuration for topics. |
| 331 |
type TopicOptions struct { |
| 332 |
// BatcherOptions adds constraints to the default batching done for sends. |
| 333 |
BatcherOptions batcher.Options |
| 334 |
} |
| 335 |
|
| 336 |
// OpenTopic returns a *pubsub.Topic backed by an existing GCP PubSub topic |
| 337 |
// in the given projectID. topicName is the last part of the full topic |
| 338 |
// path, e.g., "foo" from "projects/<projectID>/topic/foo". |
| 339 |
// See the package documentation for an example. |
| 340 |
func OpenTopic(client *raw.PublisherClient, projectID gcp.ProjectID, topicName string, opts *TopicOptions) *pubsub.Topic { |
| 341 |
topicPath := fmt.Sprintf("projects/%s/topics/%s", projectID, topicName) |
| 342 |
if opts == nil { |
| 343 |
opts = &TopicOptions{} |
| 344 |
} |
| 345 |
bo := sendBatcherOpts.NewMergedOptions(&opts.BatcherOptions) |
| 346 |
return pubsub.NewTopic(openTopic(client, topicPath), bo) |
| 347 |
} |
| 348 |
|
| 349 |
var topicPathRE = regexp.MustCompile("^projects/.+/topics/.+$") |
| 350 |
|
| 351 |
// OpenTopicByPath returns a *pubsub.Topic backed by an existing GCP PubSub |
| 352 |
// topic. topicPath must be of the form "projects/<projectID>/topic/<topic>". |
| 353 |
// See the package documentation for an example. |
| 354 |
func OpenTopicByPath(client *raw.PublisherClient, topicPath string, opts *TopicOptions) (*pubsub.Topic, error) { |
| 355 |
if !topicPathRE.MatchString(topicPath) { |
| 356 |
return nil, fmt.Errorf("invalid topicPath %q; must match %v", topicPath, topicPathRE) |
| 357 |
} |
| 358 |
if opts == nil { |
| 359 |
opts = &TopicOptions{} |
| 360 |
} |
| 361 |
bo := sendBatcherOpts.NewMergedOptions(&opts.BatcherOptions) |
| 362 |
return pubsub.NewTopic(openTopic(client, topicPath), bo), nil |
| 363 |
} |
| 364 |
|
| 365 |
// openTopic returns the driver for OpenTopic. This function exists so the test |
| 366 |
// harness can get the driver interface implementation if it needs to. |
| 367 |
func openTopic(client *raw.PublisherClient, topicPath string) driver.Topic { |
| 368 |
return &topic{topicPath, client} |
| 369 |
} |
| 370 |
|
| 371 |
// SendBatch implements driver.Topic.SendBatch. |
| 372 |
func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error { |
| 373 |
var ms []*pb.PubsubMessage |
| 374 |
for _, dm := range dms { |
| 375 |
psm := &pb.PubsubMessage{Data: dm.Body, Attributes: dm.Metadata} |
| 376 |
if dm.BeforeSend != nil { |
| 377 |
asFunc := func(i any) bool { |
| 378 |
if p, ok := i.(**pb.PubsubMessage); ok { |
| 379 |
*p = psm |
| 380 |
return true |
| 381 |
} |
| 382 |
return false |
| 383 |
} |
| 384 |
if err := dm.BeforeSend(asFunc); err != nil { |
| 385 |
return err |
| 386 |
} |
| 387 |
} |
| 388 |
ms = append(ms, psm) |
| 389 |
} |
| 390 |
req := &pb.PublishRequest{Topic: t.path, Messages: ms} |
| 391 |
pr, err := t.client.Publish(ctx, req) |
| 392 |
if err != nil { |
| 393 |
return err |
| 394 |
} |
| 395 |
if len(pr.MessageIds) == len(dms) { |
| 396 |
for n, dm := range dms { |
| 397 |
if dm.AfterSend != nil { |
| 398 |
asFunc := func(i any) bool { |
| 399 |
if p, ok := i.(*string); ok { |
| 400 |
*p = pr.MessageIds[n] |
| 401 |
return true |
| 402 |
} |
| 403 |
return false |
| 404 |
} |
| 405 |
if err := dm.AfterSend(asFunc); err != nil { |
| 406 |
return err |
| 407 |
} |
| 408 |
} |
| 409 |
} |
| 410 |
} |
| 411 |
return nil |
| 412 |
} |
| 413 |
|
| 414 |
// IsRetryable implements driver.Topic.IsRetryable. |
| 415 |
func (t *topic) IsRetryable(error) bool { |
| 416 |
// The client handles retries. |
| 417 |
return false |
| 418 |
} |
| 419 |
|
| 420 |
// As implements driver.Topic.As. |
| 421 |
func (t *topic) As(i any) bool { |
| 422 |
c, ok := i.(**raw.PublisherClient) |
| 423 |
if !ok { |
| 424 |
return false |
| 425 |
} |
| 426 |
*c = t.client |
| 427 |
return true |
| 428 |
} |
| 429 |
|
| 430 |
// ErrorAs implements driver.Topic.ErrorAs |
| 431 |
func (*topic) ErrorAs(err error, i any) bool { |
| 432 |
return errorAs(err, i) |
| 433 |
} |
| 434 |
|
| 435 |
func errorAs(err error, i any) bool { |
| 436 |
s, ok := status.FromError(err) |
| 437 |
if !ok { |
| 438 |
return false |
| 439 |
} |
| 440 |
p, ok := i.(**status.Status) |
| 441 |
if !ok { |
| 442 |
return false |
| 443 |
} |
| 444 |
*p = s |
| 445 |
return true |
| 446 |
} |
| 447 |
|
| 448 |
func (*topic) ErrorCode(err error) gcerrors.ErrorCode { |
| 449 |
return gcerr.GRPCCode(err) |
| 450 |
} |
| 451 |
|
| 452 |
// Close implements driver.Topic.Close. |
| 453 |
func (*topic) Close() error { return nil } |
| 454 |
|
| 455 |
type subscription struct { |
| 456 |
client *raw.SubscriberClient |
| 457 |
path string |
| 458 |
options *SubscriptionOptions |
| 459 |
} |
| 460 |
|
| 461 |
// SubscriptionOptions will contain configuration for subscriptions. |
| 462 |
type SubscriptionOptions struct { |
| 463 |
// MaxBatchSize caps the maximum batch size used when retrieving messages. It defaults to 1000. |
| 464 |
MaxBatchSize int |
| 465 |
|
| 466 |
// NackLazy determines what Nack does. |
| 467 |
// |
| 468 |
// By default, Nack uses ModifyAckDeadline to set the ack deadline |
| 469 |
// for the nacked message to 0, so that it will be redelivered immediately. |
| 470 |
// Set NackLazy to true to bypass this behavior; Nack will do nothing, |
| 471 |
// and the message will be redelivered after the existing ack deadline |
| 472 |
// expires. |
| 473 |
NackLazy bool |
| 474 |
|
| 475 |
// ReceiveBatcherOptions adds constraints to the default batching done for receives. |
| 476 |
ReceiveBatcherOptions batcher.Options |
| 477 |
|
| 478 |
// AckBatcherOptions adds constraints to the default batching done for acks. |
| 479 |
AckBatcherOptions batcher.Options |
| 480 |
} |
| 481 |
|
| 482 |
// OpenSubscription returns a *pubsub.Subscription backed by an existing GCP |
| 483 |
// PubSub subscription subscriptionName in the given projectID. See the package |
| 484 |
// documentation for an example. |
| 485 |
func OpenSubscription(client *raw.SubscriberClient, projectID gcp.ProjectID, subscriptionName string, opts *SubscriptionOptions) *pubsub.Subscription { |
| 486 |
path := fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subscriptionName) |
| 487 |
|
| 488 |
dsub := openSubscription(client, path, opts) |
| 489 |
recvOpts := *defaultRecvBatcherOpts |
| 490 |
recvOpts.MaxBatchSize = dsub.options.MaxBatchSize |
| 491 |
rbo := recvOpts.NewMergedOptions(&dsub.options.ReceiveBatcherOptions) |
| 492 |
abo := ackBatcherOpts.NewMergedOptions(&dsub.options.AckBatcherOptions) |
| 493 |
return pubsub.NewSubscription(dsub, rbo, abo) |
| 494 |
} |
| 495 |
|
| 496 |
var subscriptionPathRE = regexp.MustCompile("^projects/.+/subscriptions/.+$") |
| 497 |
|
| 498 |
// OpenSubscriptionByPath returns a *pubsub.Subscription backed by an existing |
| 499 |
// GCP PubSub subscription. subscriptionPath must be of the form |
| 500 |
// "projects/<projectID>/subscriptions/<subscription>". |
| 501 |
// See the package documentation for an example. |
| 502 |
func OpenSubscriptionByPath(client *raw.SubscriberClient, subscriptionPath string, opts *SubscriptionOptions) (*pubsub.Subscription, error) { |
| 503 |
if !subscriptionPathRE.MatchString(subscriptionPath) { |
| 504 |
return nil, fmt.Errorf("invalid subscriptionPath %q; must match %v", subscriptionPath, subscriptionPathRE) |
| 505 |
} |
| 506 |
|
| 507 |
dsub := openSubscription(client, subscriptionPath, opts) |
| 508 |
recvOpts := *defaultRecvBatcherOpts |
| 509 |
recvOpts.MaxBatchSize = dsub.options.MaxBatchSize |
| 510 |
rbo := recvOpts.NewMergedOptions(&dsub.options.ReceiveBatcherOptions) |
| 511 |
abo := ackBatcherOpts.NewMergedOptions(&dsub.options.AckBatcherOptions) |
| 512 |
return pubsub.NewSubscription(dsub, rbo, abo), nil |
| 513 |
} |
| 514 |
|
| 515 |
// openSubscription returns a driver.Subscription. |
| 516 |
func openSubscription(client *raw.SubscriberClient, subscriptionPath string, opts *SubscriptionOptions) *subscription { |
| 517 |
if opts == nil { |
| 518 |
opts = &SubscriptionOptions{} |
| 519 |
} |
| 520 |
if opts.MaxBatchSize == 0 { |
| 521 |
opts.MaxBatchSize = defaultRecvBatcherOpts.MaxBatchSize |
| 522 |
} |
| 523 |
return &subscription{client, subscriptionPath, opts} |
| 524 |
} |
| 525 |
|
| 526 |
// ReceiveBatch implements driver.Subscription.ReceiveBatch. |
| 527 |
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) { |
| 528 |
// Whether to ask Pull to return immediately, or wait for some messages to |
| 529 |
// arrive. If we're making multiple RPCs, we don't want any of them to wait; |
| 530 |
// we might have gotten messages from one of the other RPCs. |
| 531 |
// maxMessages will only be high enough to set this to true in high-throughput |
| 532 |
// situations, so the likelihood of getting 0 messages is small anyway. |
| 533 |
returnImmediately := maxMessages == s.options.MaxBatchSize |
| 534 |
|
| 535 |
req := &pb.PullRequest{ |
| 536 |
Subscription: s.path, |
| 537 |
ReturnImmediately: returnImmediately, |
| 538 |
MaxMessages: int32(maxMessages), |
| 539 |
} |
| 540 |
resp, err := s.client.Pull(ctx, req) |
| 541 |
if err != nil { |
| 542 |
return nil, err |
| 543 |
} |
| 544 |
if len(resp.ReceivedMessages) == 0 { |
| 545 |
// If we did happen to get 0 messages, and we didn't ask the server to wait |
| 546 |
// for messages, sleep a bit to avoid spinning. |
| 547 |
if returnImmediately { |
| 548 |
time.Sleep(100 * time.Millisecond) |
| 549 |
} |
| 550 |
return nil, nil |
| 551 |
} |
| 552 |
|
| 553 |
ms := make([]*driver.Message, 0, len(resp.ReceivedMessages)) |
| 554 |
for _, rm := range resp.ReceivedMessages { |
| 555 |
rmm := rm.Message |
| 556 |
m := &driver.Message{ |
| 557 |
LoggableID: rmm.MessageId, |
| 558 |
Body: rmm.Data, |
| 559 |
Metadata: rmm.Attributes, |
| 560 |
AckID: rm.AckId, |
| 561 |
AsFunc: messageAsFunc(rmm, rm), |
| 562 |
} |
| 563 |
ms = append(ms, m) |
| 564 |
} |
| 565 |
return ms, nil |
| 566 |
} |
| 567 |
|
| 568 |
func messageAsFunc(pm *pb.PubsubMessage, rm *pb.ReceivedMessage) func(any) bool { |
| 569 |
return func(i any) bool { |
| 570 |
ip, ok := i.(**pb.PubsubMessage) |
| 571 |
if ok { |
| 572 |
*ip = pm |
| 573 |
return true |
| 574 |
} |
| 575 |
rp, ok := i.(**pb.ReceivedMessage) |
| 576 |
if ok { |
| 577 |
*rp = rm |
| 578 |
return true |
| 579 |
} |
| 580 |
return false |
| 581 |
} |
| 582 |
} |
| 583 |
|
| 584 |
// SendAcks implements driver.Subscription.SendAcks. |
| 585 |
func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error { |
| 586 |
ids2 := make([]string, 0, len(ids)) |
| 587 |
for _, id := range ids { |
| 588 |
ids2 = append(ids2, id.(string)) |
| 589 |
} |
| 590 |
return s.client.Acknowledge(ctx, &pb.AcknowledgeRequest{Subscription: s.path, AckIds: ids2}) |
| 591 |
} |
| 592 |
|
| 593 |
// CanNack implements driver.CanNack. |
| 594 |
func (s *subscription) CanNack() bool { return true } |
| 595 |
|
| 596 |
// SendNacks implements driver.Subscription.SendNacks. |
| 597 |
func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error { |
| 598 |
if s.options.NackLazy { |
| 599 |
return nil |
| 600 |
} |
| 601 |
ids2 := make([]string, 0, len(ids)) |
| 602 |
for _, id := range ids { |
| 603 |
ids2 = append(ids2, id.(string)) |
| 604 |
} |
| 605 |
return s.client.ModifyAckDeadline(ctx, &pb.ModifyAckDeadlineRequest{ |
| 606 |
Subscription: s.path, |
| 607 |
AckIds: ids2, |
| 608 |
AckDeadlineSeconds: 0, |
| 609 |
}) |
| 610 |
} |
| 611 |
|
| 612 |
// IsRetryable implements driver.Subscription.IsRetryable. |
| 613 |
func (s *subscription) IsRetryable(err error) bool { |
| 614 |
// The client mostly handles retries, but does not |
| 615 |
// include DeadlineExceeded for some reason. |
| 616 |
return s.ErrorCode(err) == gcerrors.DeadlineExceeded |
| 617 |
} |
| 618 |
|
| 619 |
// As implements driver.Subscription.As. |
| 620 |
func (s *subscription) As(i any) bool { |
| 621 |
c, ok := i.(**raw.SubscriberClient) |
| 622 |
if !ok { |
| 623 |
return false |
| 624 |
} |
| 625 |
*c = s.client |
| 626 |
return true |
| 627 |
} |
| 628 |
|
| 629 |
// ErrorAs implements driver.Subscription.ErrorAs |
| 630 |
func (*subscription) ErrorAs(err error, i any) bool { |
| 631 |
return errorAs(err, i) |
| 632 |
} |
| 633 |
|
| 634 |
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode { |
| 635 |
return gcerr.GRPCCode(err) |
| 636 |
} |
| 637 |
|
| 638 |
// Close implements driver.Subscription.Close. |
| 639 |
func (*subscription) Close() error { return nil } |
| 640 |
|
| 641 |
func queryParameterInt(value []string) (int, error) { |
| 642 |
if len(value) > 1 { |
| 643 |
return 0, fmt.Errorf("expected only one parameter value, got: %v", len(value)) |
| 644 |
} |
| 645 |
|
| 646 |
return strconv.Atoi(value[0]) |
| 647 |
} |
| 648 |
|
| 649 |
func queryParameterBool(value []string) (bool, error) { |
| 650 |
if len(value) > 1 { |
| 651 |
return false, fmt.Errorf("expected only one parameter value, got: %v", len(value)) |
| 652 |
} |
| 653 |
|
| 654 |
return strconv.ParseBool(value[0]) |
| 655 |
} |