| 1 |
// Copyright 2025 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, gcppubsubv2 registers |
| 22 |
// for the scheme "gcppubsubv2". |
| 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 |
// gcppubsubv2 exposes the following types for As: |
| 44 |
// - Topic: *raw.Publisher |
| 45 |
// - Subscription: *raw.Subscriber |
| 46 |
// - Message.BeforeSend: *raw.Message |
| 47 |
// - Message.AfterSend: *string for the raw.PublishResult serverID corresponding to the message. |
| 48 |
// - Message: *raw.Message |
| 49 |
// - Error: *google.golang.org/grpc/status.Status |
| 50 |
package gcppubsubv2 // import "gocloud.dev/pubsub/gcppubsubv2" |
| 51 |
|
| 52 |
import ( |
| 53 |
"context" |
| 54 |
"errors" |
| 55 |
"fmt" |
| 56 |
"net/url" |
| 57 |
"os" |
| 58 |
"path" |
| 59 |
"regexp" |
| 60 |
"strconv" |
| 61 |
"strings" |
| 62 |
"sync" |
| 63 |
"time" |
| 64 |
|
| 65 |
raw "cloud.google.com/go/pubsub/v2" |
| 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 |
// The underlying library does its own batching, so for throughput |
| 86 |
// what we pick here doesn't matter much. It's simpler and more |
| 87 |
// likely to elicit good behavior from the underlying library to |
| 88 |
// do one message at a time. It also results in clearer errors, |
| 89 |
// at least back to the concrete type, because returning an error |
| 90 |
// from SendBatch when some messages were sent and others weren't |
| 91 |
// is always a bit unfortunate. |
| 92 |
MaxBatchSize: 1, |
| 93 |
MaxHandlers: 1000, |
| 94 |
} |
| 95 |
|
| 96 |
var defaultRecvBatcherOpts = &batcher.Options{ |
| 97 |
// Single threaded; v2 wants only a single Receive. We get concurrency |
| 98 |
// via concurrent callbacks; the resulting messages are buffered |
| 99 |
// in memory until they can be returned via ReceiveBatch. When that |
| 100 |
// happens, we might as well return a lot of them. |
| 101 |
MaxBatchSize: 5000, |
| 102 |
MaxHandlers: 1, |
| 103 |
} |
| 104 |
|
| 105 |
var ackBatcherOpts = &batcher.Options{ |
| 106 |
// Similar to SendBatch. |
| 107 |
MaxBatchSize: 1, |
| 108 |
MaxHandlers: 1000, |
| 109 |
} |
| 110 |
|
| 111 |
func init() { |
| 112 |
o := new(lazyCredsOpener) |
| 113 |
pubsub.DefaultURLMux().RegisterTopic(Scheme, o) |
| 114 |
pubsub.DefaultURLMux().RegisterSubscription(Scheme, o) |
| 115 |
} |
| 116 |
|
| 117 |
// Set holds Wire providers for this package. |
| 118 |
var Set = wire.NewSet( |
| 119 |
Dial, |
| 120 |
Client, |
| 121 |
wire.Struct(new(SubscriptionOptions)), |
| 122 |
wire.Struct(new(TopicOptions)), |
| 123 |
wire.Struct(new(URLOpener), "Conn", "TopicOptions", "SubscriptionOptions"), |
| 124 |
) |
| 125 |
|
| 126 |
// lazyCredsOpener obtains Application Default Credentials on the first call |
| 127 |
// to OpenTopicURL/OpenSubscriptionURL. |
| 128 |
type lazyCredsOpener struct { |
| 129 |
init sync.Once |
| 130 |
opener *URLOpener |
| 131 |
err error |
| 132 |
} |
| 133 |
|
| 134 |
func (o *lazyCredsOpener) defaultConn(ctx context.Context) (*URLOpener, error) { |
| 135 |
o.init.Do(func() { |
| 136 |
var conn *grpc.ClientConn |
| 137 |
var err error |
| 138 |
if e := os.Getenv("PUBSUB_EMULATOR_HOST"); e != "" { |
| 139 |
// Connect to the GCP pubsub emulator by overriding the default endpoint |
| 140 |
// if the 'PUBSUB_EMULATOR_HOST' environment variable is set. |
| 141 |
// Check https://cloud.google.com/pubsub/docs/emulator for more info. |
| 142 |
endPoint = e |
| 143 |
conn, err = dialEmulator(ctx, e) |
| 144 |
if err != nil { |
| 145 |
o.err = err |
| 146 |
return |
| 147 |
} |
| 148 |
} else { |
| 149 |
creds, err := gcp.DefaultCredentials(ctx) |
| 150 |
if err != nil { |
| 151 |
o.err = err |
| 152 |
return |
| 153 |
} |
| 154 |
|
| 155 |
conn, _, err = Dial(ctx, creds.TokenSource) |
| 156 |
if err != nil { |
| 157 |
o.err = err |
| 158 |
return |
| 159 |
} |
| 160 |
} |
| 161 |
o.opener = &URLOpener{Conn: conn} |
| 162 |
}) |
| 163 |
return o.opener, o.err |
| 164 |
} |
| 165 |
|
| 166 |
func (o *lazyCredsOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 167 |
opener, err := o.defaultConn(ctx) |
| 168 |
if err != nil { |
| 169 |
return nil, fmt.Errorf("open topic %v: failed to open default connection: %v", u, err) |
| 170 |
} |
| 171 |
return opener.OpenTopicURL(ctx, u) |
| 172 |
} |
| 173 |
|
| 174 |
func (o *lazyCredsOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 175 |
opener, err := o.defaultConn(ctx) |
| 176 |
if err != nil { |
| 177 |
return nil, fmt.Errorf("open subscription %v: failed to open default connection: %v", u, err) |
| 178 |
} |
| 179 |
return opener.OpenSubscriptionURL(ctx, u) |
| 180 |
} |
| 181 |
|
| 182 |
// Scheme is the URL scheme gcppubsubv2 registers its URLOpeners under on pubsub.DefaultMux. |
| 183 |
const Scheme = "gcppubsubv2" |
| 184 |
|
| 185 |
// URLOpener opens GCP Pub/Sub URLs like "gcppubsubv2://projects/myproject/topics/mytopic" for |
| 186 |
// topics or "gcppubsubv2://projects/myproject/subscriptions/mysub" for subscriptions. |
| 187 |
// |
| 188 |
// The shortened forms "gcppubsubv2://myproject/mytopic" for topics or |
| 189 |
// "gcppubsubv2://myproject/mysub" for subscriptions are also supported. |
| 190 |
// |
| 191 |
// The following query parameters are supported: |
| 192 |
// |
| 193 |
// - max_recv_batch_size: sets SubscriptionOptions.MaxBatchSize. |
| 194 |
// - max_send_batch_size: sets TopicOptions.BatcherOptions.MaxBatchSize. |
| 195 |
// |
| 196 |
// Currently their use is limited to subscribers. |
| 197 |
type URLOpener struct { |
| 198 |
// Conn must be set to a non-nil ClientConn authenticated with |
| 199 |
// Cloud Pub/Sub scope or equivalent. |
| 200 |
Conn *grpc.ClientConn |
| 201 |
|
| 202 |
// TopicOptions specifies the options to pass to OpenTopic. |
| 203 |
TopicOptions TopicOptions |
| 204 |
// SubscriptionOptions specifies the options to pass to OpenSubscription. |
| 205 |
SubscriptionOptions SubscriptionOptions |
| 206 |
} |
| 207 |
|
| 208 |
// OpenTopicURL opens a pubsub.Topic based on u. |
| 209 |
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) { |
| 210 |
opts := o.TopicOptions |
| 211 |
|
| 212 |
for param, value := range u.Query() { |
| 213 |
switch param { |
| 214 |
case "max_send_batch_size": |
| 215 |
maxBatchSize, err := queryParameterInt(value) |
| 216 |
if err != nil { |
| 217 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q: %v", u, param, err) |
| 218 |
} |
| 219 |
|
| 220 |
if maxBatchSize <= 0 || maxBatchSize > 1000 { |
| 221 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q: must be between 1 and 1000", u, param) |
| 222 |
} |
| 223 |
|
| 224 |
opts.BatcherOptions.MaxBatchSize = maxBatchSize |
| 225 |
default: |
| 226 |
return nil, fmt.Errorf("open topic %v: invalid query parameter %q", u, param) |
| 227 |
} |
| 228 |
} |
| 229 |
client, err := Client(ctx, gcp.ProjectID(u.Host), o.Conn) |
| 230 |
if err != nil { |
| 231 |
return nil, err |
| 232 |
} |
| 233 |
topicPath := path.Join(u.Host, u.Path) |
| 234 |
if topicPathRE.MatchString(topicPath) { |
| 235 |
return OpenTopicByPath(client, topicPath, &opts) |
| 236 |
} |
| 237 |
// Shortened form? |
| 238 |
topicName := strings.TrimPrefix(u.Path, "/") |
| 239 |
return OpenTopic(client, topicName, &opts), nil |
| 240 |
} |
| 241 |
|
| 242 |
// OpenSubscriptionURL opens a pubsub.Subscription based on u. |
| 243 |
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) { |
| 244 |
// Set subscription options to use defaults |
| 245 |
opts := o.SubscriptionOptions |
| 246 |
|
| 247 |
for param, value := range u.Query() { |
| 248 |
switch param { |
| 249 |
case "max_recv_batch_size": |
| 250 |
maxBatchSize, err := queryParameterInt(value) |
| 251 |
if err != nil { |
| 252 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: %v", u, param, err) |
| 253 |
} |
| 254 |
|
| 255 |
if maxBatchSize <= 0 || maxBatchSize > 1000 { |
| 256 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q: must be between 1 and 1000", u, param) |
| 257 |
} |
| 258 |
|
| 259 |
opts.MaxBatchSize = maxBatchSize |
| 260 |
default: |
| 261 |
return nil, fmt.Errorf("open subscription %v: invalid query parameter %q", u, param) |
| 262 |
} |
| 263 |
} |
| 264 |
client, err := Client(ctx, gcp.ProjectID(u.Host), o.Conn) |
| 265 |
if err != nil { |
| 266 |
return nil, err |
| 267 |
} |
| 268 |
subPath := path.Join(u.Host, u.Path) |
| 269 |
if subscriptionPathRE.MatchString(subPath) { |
| 270 |
return OpenSubscriptionByPath(client, subPath, &opts) |
| 271 |
} |
| 272 |
// Shortened form? |
| 273 |
subName := strings.TrimPrefix(u.Path, "/") |
| 274 |
return OpenSubscription(client, subName, &opts), nil |
| 275 |
} |
| 276 |
|
| 277 |
type topic struct { |
| 278 |
publisher *raw.Publisher |
| 279 |
} |
| 280 |
|
| 281 |
// Dial opens a gRPC connection to the GCP Pub Sub API. |
| 282 |
// |
| 283 |
// The second return value is a function that can be called to clean up |
| 284 |
// the connection opened by Dial. |
| 285 |
func Dial(ctx context.Context, ts gcp.TokenSource) (*grpc.ClientConn, func(), error) { |
| 286 |
conn, err := grpc.DialContext(ctx, endPoint, |
| 287 |
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")), |
| 288 |
grpc.WithPerRPCCredentials(oauth.TokenSource{TokenSource: ts}), |
| 289 |
// The default message size limit for gRPC is 4MB, while GCP |
| 290 |
// PubSub supports messages up to 10MB. Aside from the message itself |
| 291 |
// there is also other data in the gRPC response, bringing the maximum |
| 292 |
// response size above 10MB. Tell gRPC to support up to 11MB. |
| 293 |
// https://github.com/googleapis/google-cloud-node/issues/1991 |
| 294 |
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(1024*1024*11)), |
| 295 |
useragent.GRPCDialOption("pubsub"), |
| 296 |
) |
| 297 |
if err != nil { |
| 298 |
return nil, nil, err |
| 299 |
} |
| 300 |
return conn, func() { conn.Close() }, nil |
| 301 |
} |
| 302 |
|
| 303 |
// dialEmulator opens a gRPC connection to the GCP Pub Sub API. |
| 304 |
func dialEmulator(ctx context.Context, e string) (*grpc.ClientConn, error) { |
| 305 |
conn, err := grpc.DialContext(ctx, e, |
| 306 |
grpc.WithTransportCredentials(insecure.NewCredentials()), |
| 307 |
useragent.GRPCDialOption("pubsub")) |
| 308 |
if err != nil { |
| 309 |
return nil, err |
| 310 |
} |
| 311 |
return conn, nil |
| 312 |
} |
| 313 |
|
| 314 |
// Client returns a *raw.Client that can be used in OpenTopic and/or OpenSubscription. |
| 315 |
// conn is optional. |
| 316 |
func Client(ctx context.Context, projectID gcp.ProjectID, conn *grpc.ClientConn) (*raw.Client, error) { |
| 317 |
if conn == nil { |
| 318 |
return raw.NewClient(ctx, string(projectID)) |
| 319 |
} |
| 320 |
return raw.NewClient(ctx, string(projectID), option.WithGRPCConn(conn)) |
| 321 |
} |
| 322 |
|
| 323 |
// TopicOptions will contain configuration for topics. |
| 324 |
type TopicOptions struct { |
| 325 |
// BatcherOptions adds constraints to the default batching done for sends. |
| 326 |
BatcherOptions batcher.Options |
| 327 |
} |
| 328 |
|
| 329 |
// OpenTopic returns a *pubsub.Topic backed by an existing GCP PubSub topic |
| 330 |
// topicName is the last part of the full topic path, e.g., "foo" from "projects/<projectID>/topic/foo". |
| 331 |
// See the package documentation for an example. |
| 332 |
func OpenTopic(client *raw.Client, topicName string, opts *TopicOptions) *pubsub.Topic { |
| 333 |
publisher := client.Publisher(topicName) |
| 334 |
if opts == nil { |
| 335 |
opts = &TopicOptions{} |
| 336 |
} |
| 337 |
bo := sendBatcherOpts.NewMergedOptions(&opts.BatcherOptions) |
| 338 |
return pubsub.NewTopic(openTopic(publisher), bo) |
| 339 |
} |
| 340 |
|
| 341 |
var topicPathRE = regexp.MustCompile("^projects/.+/topics/(.+)$") |
| 342 |
|
| 343 |
// OpenTopicByPath returns a *pubsub.Topic backed by an existing GCP PubSub |
| 344 |
// topic. topicPath must be of the form "projects/<projectID>/topic/<topic>". |
| 345 |
// See the package documentation for an example. |
| 346 |
func OpenTopicByPath(client *raw.Client, topicPath string, opts *TopicOptions) (*pubsub.Topic, error) { |
| 347 |
matches := topicPathRE.FindStringSubmatch(topicPath) |
| 348 |
if len(matches) != 2 { |
| 349 |
return nil, fmt.Errorf("invalid topicPath %q; must match %v", topicPath, topicPathRE) |
| 350 |
} |
| 351 |
topicName := matches[1] |
| 352 |
return OpenTopic(client, topicName, opts), nil |
| 353 |
} |
| 354 |
|
| 355 |
// openTopic returns the driver for OpenTopic. This function exists so the test |
| 356 |
// harness can get the driver interface implementation if it needs to. |
| 357 |
func openTopic(publisher *raw.Publisher) driver.Topic { |
| 358 |
return &topic{publisher} |
| 359 |
} |
| 360 |
|
| 361 |
// SendBatch implements driver.Topic.SendBatch. |
| 362 |
func (t *topic) SendBatch(ctx context.Context, dms []*driver.Message) error { |
| 363 |
var results []*raw.PublishResult |
| 364 |
for _, dm := range dms { |
| 365 |
psm := &raw.Message{Data: dm.Body, Attributes: dm.Metadata} |
| 366 |
if dm.BeforeSend != nil { |
| 367 |
asFunc := func(i any) bool { |
| 368 |
if p, ok := i.(**raw.Message); ok { |
| 369 |
*p = psm |
| 370 |
return true |
| 371 |
} |
| 372 |
return false |
| 373 |
} |
| 374 |
if err := dm.BeforeSend(asFunc); err != nil { |
| 375 |
return err |
| 376 |
} |
| 377 |
} |
| 378 |
// Publish always returns immediately; the return value's Get |
| 379 |
// function blocks until there's a result. |
| 380 |
results = append(results, t.publisher.Publish(ctx, psm)) |
| 381 |
} |
| 382 |
for n, dm := range dms { |
| 383 |
pr := results[n] |
| 384 |
messageID, err := pr.Get(ctx) |
| 385 |
if err != nil { |
| 386 |
return err |
| 387 |
} |
| 388 |
if dm.AfterSend != nil { |
| 389 |
asFunc := func(i any) bool { |
| 390 |
if p, ok := i.(*string); ok { |
| 391 |
*p = messageID |
| 392 |
return true |
| 393 |
} |
| 394 |
return false |
| 395 |
} |
| 396 |
if err := dm.AfterSend(asFunc); err != nil { |
| 397 |
return err |
| 398 |
} |
| 399 |
} |
| 400 |
} |
| 401 |
return nil |
| 402 |
} |
| 403 |
|
| 404 |
// IsRetryable implements driver.Topic.IsRetryable. |
| 405 |
func (t *topic) IsRetryable(error) bool { |
| 406 |
// The client handles retries. |
| 407 |
return false |
| 408 |
} |
| 409 |
|
| 410 |
// As implements driver.Topic.As. |
| 411 |
func (t *topic) As(i any) bool { |
| 412 |
c, ok := i.(**raw.Publisher) |
| 413 |
if !ok { |
| 414 |
return false |
| 415 |
} |
| 416 |
*c = t.publisher |
| 417 |
return true |
| 418 |
} |
| 419 |
|
| 420 |
// ErrorAs implements driver.Topic.ErrorAs |
| 421 |
func (*topic) ErrorAs(err error, i any) bool { |
| 422 |
return errorAs(err, i) |
| 423 |
} |
| 424 |
|
| 425 |
func errorAs(err error, i any) bool { |
| 426 |
s, ok := status.FromError(err) |
| 427 |
if !ok { |
| 428 |
return false |
| 429 |
} |
| 430 |
p, ok := i.(**status.Status) |
| 431 |
if !ok { |
| 432 |
return false |
| 433 |
} |
| 434 |
*p = s |
| 435 |
return true |
| 436 |
} |
| 437 |
|
| 438 |
func (*topic) ErrorCode(err error) gcerrors.ErrorCode { |
| 439 |
return gcerr.GRPCCode(err) |
| 440 |
} |
| 441 |
|
| 442 |
// Close implements driver.Topic.Close. |
| 443 |
func (*topic) Close() error { return nil } |
| 444 |
|
| 445 |
type ackableMsg struct { |
| 446 |
rawm *raw.Message |
| 447 |
ch chan bool |
| 448 |
} |
| 449 |
|
| 450 |
type subscription struct { |
| 451 |
subscriber *raw.Subscriber |
| 452 |
options *SubscriptionOptions |
| 453 |
|
| 454 |
// Fields for managing the single Receive RPC called in the background. |
| 455 |
receiving bool // true when there's an active RPC |
| 456 |
receiveCtx context.Context // the single background context used when calling Receive |
| 457 |
receiveCancel func() // cancel func for receiveCtx; called during Close |
| 458 |
|
| 459 |
// Fields used for managing buffered messages. |
| 460 |
mu sync.Mutex |
| 461 |
dms []*driver.Message // buffered messages for next ReceiveBatch |
| 462 |
receiveErr error // error returned by last Receive, to be returned by next ReceiveBatch |
| 463 |
acks map[driver.AckID]*ackableMsg // returned messages that haven't yet been acked/nacked |
| 464 |
} |
| 465 |
|
| 466 |
// SubscriptionOptions will contain configuration for subscriptions. |
| 467 |
type SubscriptionOptions struct { |
| 468 |
// MaxBatchSize caps the maximum batch size used when retrieving messages. It defaults to 1000. |
| 469 |
MaxBatchSize int |
| 470 |
|
| 471 |
// ReceiveBatcherOptions adds constraints to the default batching done for receives. |
| 472 |
ReceiveBatcherOptions batcher.Options |
| 473 |
|
| 474 |
// AckBatcherOptions adds constraints to the default batching done for acks. |
| 475 |
AckBatcherOptions batcher.Options |
| 476 |
} |
| 477 |
|
| 478 |
// OpenSubscription returns a *pubsub.Subscription backed by an existing GCP |
| 479 |
// PubSub subscription subscriptionName. See the package documentation for an example. |
| 480 |
func OpenSubscription(client *raw.Client, subscriptionName string, opts *SubscriptionOptions) *pubsub.Subscription { |
| 481 |
subscriber := client.Subscriber(subscriptionName) |
| 482 |
dsub := openSubscription(subscriber, opts) |
| 483 |
recvOpts := *defaultRecvBatcherOpts |
| 484 |
recvOpts.MaxBatchSize = dsub.options.MaxBatchSize |
| 485 |
rbo := recvOpts.NewMergedOptions(&dsub.options.ReceiveBatcherOptions) |
| 486 |
abo := ackBatcherOpts.NewMergedOptions(&dsub.options.AckBatcherOptions) |
| 487 |
return pubsub.NewSubscription(dsub, rbo, abo) |
| 488 |
} |
| 489 |
|
| 490 |
var subscriptionPathRE = regexp.MustCompile("^projects/.+/subscriptions/(.+)$") |
| 491 |
|
| 492 |
// OpenSubscriptionByPath returns a *pubsub.Subscription backed by an existing |
| 493 |
// GCP PubSub subscription. subscriptionPath must be of the form |
| 494 |
// "projects/<projectID>/subscriptions/<subscription>". |
| 495 |
// See the package documentation for an example. |
| 496 |
func OpenSubscriptionByPath(client *raw.Client, subscriptionPath string, opts *SubscriptionOptions) (*pubsub.Subscription, error) { |
| 497 |
matches := subscriptionPathRE.FindStringSubmatch(subscriptionPath) |
| 498 |
if len(matches) != 2 { |
| 499 |
return nil, fmt.Errorf("invalid subscriptionPath %q; must match %v", subscriptionPath, subscriptionPathRE) |
| 500 |
} |
| 501 |
subscriptionName := matches[1] |
| 502 |
return OpenSubscription(client, subscriptionName, opts), nil |
| 503 |
} |
| 504 |
|
| 505 |
// openSubscription returns a driver.Subscription. |
| 506 |
func openSubscription(subscriber *raw.Subscriber, opts *SubscriptionOptions) *subscription { |
| 507 |
if opts == nil { |
| 508 |
opts = &SubscriptionOptions{} |
| 509 |
} |
| 510 |
if opts.MaxBatchSize == 0 { |
| 511 |
opts.MaxBatchSize = defaultRecvBatcherOpts.MaxBatchSize |
| 512 |
} |
| 513 |
// Construct a context that's used (repeatedly if necessary) to call Receive. |
| 514 |
// It never expires; the Receive may last forever. |
| 515 |
// The cancel function is used during shutdown. |
| 516 |
ctx, cancel := context.WithCancel(context.Background()) |
| 517 |
return &subscription{ |
| 518 |
subscriber: subscriber, |
| 519 |
options: opts, |
| 520 |
receiving: false, |
| 521 |
receiveCtx: ctx, |
| 522 |
receiveCancel: cancel, |
| 523 |
acks: map[driver.AckID]*ackableMsg{}, |
| 524 |
} |
| 525 |
} |
| 526 |
|
| 527 |
// ReceiveBatch implements driver.Subscription.ReceiveBatch. |
| 528 |
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) { |
| 529 |
s.mu.Lock() |
| 530 |
defer s.mu.Unlock() |
| 531 |
if !s.receiving { |
| 532 |
// Start up the goroutine that calls Receive. |
| 533 |
s.receiving = true |
| 534 |
go func() { |
| 535 |
// Receive blocks until receiveCtx ends, which will only happen during shutdown, |
| 536 |
// or if there's a fatal error. |
| 537 |
// During normal use, this goroutine will sit here in Receive, |
| 538 |
// the underlying library will call the callback as messages arrive, |
| 539 |
// the callback implementation will add them to s.dms, and |
| 540 |
// ReceiveBatch will pull them off. |
| 541 |
// |
| 542 |
// The underlying library *requires* that Ack or Nack be called inside the |
| 543 |
// callback. Therefore, after adding the message to s.dms, the callback |
| 544 |
// (which is running in its own goroutine from the underlying library) |
| 545 |
// creates a channel and waits on it; Ack/Nack will write true/false to that |
| 546 |
// channel, allowing the callback to finally return. |
| 547 |
err := s.subscriber.Receive(s.receiveCtx, func(ctx context.Context, rawm *raw.Message) { |
| 548 |
dm := &driver.Message{ |
| 549 |
LoggableID: rawm.ID, |
| 550 |
Body: rawm.Data, |
| 551 |
Metadata: rawm.Attributes, |
| 552 |
AckID: driver.AckID(rawm.ID), |
| 553 |
AsFunc: func(i any) bool { |
| 554 |
rm, ok := i.(**raw.Message) |
| 555 |
if ok { |
| 556 |
*rm = rawm |
| 557 |
return true |
| 558 |
} |
| 559 |
return false |
| 560 |
}, |
| 561 |
} |
| 562 |
// As described above, ackCh will be used to wait here until |
| 563 |
// Ack or Nack is called. |
| 564 |
ackCh := make(chan bool) |
| 565 |
s.mu.Lock() |
| 566 |
s.acks[rawm.ID] = &ackableMsg{rawm, ackCh} |
| 567 |
s.dms = append(s.dms, dm) |
| 568 |
s.mu.Unlock() |
| 569 |
isAck := <-ackCh |
| 570 |
if isAck { |
| 571 |
rawm.Ack() |
| 572 |
} else { |
| 573 |
rawm.Nack() |
| 574 |
} |
| 575 |
}) |
| 576 |
// Receive returned. Either we're shutting down, or there's a permanent error. |
| 577 |
// Either way, reset so that if ReceiveBatch is called again, we'll retry. |
| 578 |
s.mu.Lock() |
| 579 |
if !errors.Is(err, context.Canceled) { |
| 580 |
s.receiveErr = err |
| 581 |
} |
| 582 |
s.receiving = false |
| 583 |
s.mu.Unlock() |
| 584 |
}() |
| 585 |
} |
| 586 |
|
| 587 |
// Return up to maxMessages from the buffer. |
| 588 |
var dms []*driver.Message |
| 589 |
if err := s.receiveErr; err != nil { |
| 590 |
s.receiveErr = nil |
| 591 |
return nil, err |
| 592 |
} |
| 593 |
if len(s.dms) <= maxMessages { |
| 594 |
dms = s.dms |
| 595 |
s.dms = nil |
| 596 |
} else { |
| 597 |
dms = s.dms[0:maxMessages] |
| 598 |
s.dms = s.dms[maxMessages:] |
| 599 |
} |
| 600 |
if len(dms) == 0 { |
| 601 |
time.Sleep(100 * time.Millisecond) |
| 602 |
return nil, nil |
| 603 |
} |
| 604 |
return dms, nil |
| 605 |
} |
| 606 |
|
| 607 |
// SendAcks implements driver.Subscription.SendAcks. |
| 608 |
func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error { |
| 609 |
s.mu.Lock() |
| 610 |
defer s.mu.Unlock() |
| 611 |
for _, id := range ids { |
| 612 |
if ackable := s.acks[id]; ackable != nil { |
| 613 |
ackable.ch <- true |
| 614 |
close(ackable.ch) |
| 615 |
delete(s.acks, id) |
| 616 |
} |
| 617 |
} |
| 618 |
return nil |
| 619 |
} |
| 620 |
|
| 621 |
// CanNack implements driver.CanNack. |
| 622 |
func (s *subscription) CanNack() bool { return true } |
| 623 |
|
| 624 |
// SendNacks implements driver.Subscription.SendNacks. |
| 625 |
func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error { |
| 626 |
s.mu.Lock() |
| 627 |
defer s.mu.Unlock() |
| 628 |
for _, id := range ids { |
| 629 |
if ackable := s.acks[id]; ackable != nil { |
| 630 |
ackable.ch <- false |
| 631 |
close(ackable.ch) |
| 632 |
delete(s.acks, id) |
| 633 |
} |
| 634 |
} |
| 635 |
return nil |
| 636 |
} |
| 637 |
|
| 638 |
// IsRetryable implements driver.Subscription.IsRetryable. |
| 639 |
func (s *subscription) IsRetryable(err error) bool { |
| 640 |
// The client mostly handles retries, but does not |
| 641 |
// include DeadlineExceeded for some reason. |
| 642 |
return s.ErrorCode(err) == gcerrors.DeadlineExceeded |
| 643 |
} |
| 644 |
|
| 645 |
// As implements driver.Subscription.As. |
| 646 |
func (s *subscription) As(i any) bool { |
| 647 |
c, ok := i.(**raw.Subscriber) |
| 648 |
if !ok { |
| 649 |
return false |
| 650 |
} |
| 651 |
*c = s.subscriber |
| 652 |
return true |
| 653 |
} |
| 654 |
|
| 655 |
// ErrorAs implements driver.Subscription.ErrorAs |
| 656 |
func (*subscription) ErrorAs(err error, i any) bool { |
| 657 |
return errorAs(err, i) |
| 658 |
} |
| 659 |
|
| 660 |
func (*subscription) ErrorCode(err error) gcerrors.ErrorCode { |
| 661 |
return gcerr.GRPCCode(err) |
| 662 |
} |
| 663 |
|
| 664 |
// Close implements driver.Subscription.Close. |
| 665 |
func (s *subscription) Close() error { |
| 666 |
s.receiveCancel() |
| 667 |
return nil |
| 668 |
} |
| 669 |
|
| 670 |
func queryParameterInt(value []string) (int, error) { |
| 671 |
if len(value) > 1 { |
| 672 |
return 0, fmt.Errorf("expected only one parameter value, got: %v", len(value)) |
| 673 |
} |
| 674 |
|
| 675 |
return strconv.Atoi(value[0]) |
| 676 |
} |