| 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 gcppubsubv2 |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"fmt" |
| 20 |
"path" |
| 21 |
"strings" |
| 22 |
"sync/atomic" |
| 23 |
"testing" |
| 24 |
|
| 25 |
raw "cloud.google.com/go/pubsub/v2" |
| 26 |
"cloud.google.com/go/pubsub/v2/apiv1/pubsubpb" |
| 27 |
"gocloud.dev/gcp" |
| 28 |
"gocloud.dev/internal/testing/setup" |
| 29 |
"gocloud.dev/pubsub" |
| 30 |
"gocloud.dev/pubsub/driver" |
| 31 |
"gocloud.dev/pubsub/drivertest" |
| 32 |
"google.golang.org/grpc/codes" |
| 33 |
"google.golang.org/grpc/status" |
| 34 |
) |
| 35 |
|
| 36 |
// projectID is the project ID that was used during the last test run using |
| 37 |
// --record. |
| 38 |
const projectID = "go-cloud-test-216917" |
| 39 |
|
| 40 |
type harness struct { |
| 41 |
closer func() |
| 42 |
client *raw.Client |
| 43 |
numTopics uint32 // atomic |
| 44 |
numSubs uint32 // atomic |
| 45 |
} |
| 46 |
|
| 47 |
func newHarness(ctx context.Context, t *testing.T) (drivertest.Harness, error) { |
| 48 |
t.Helper() |
| 49 |
|
| 50 |
client, err := Client(ctx, projectID, nil) |
| 51 |
if err != nil { |
| 52 |
return nil, fmt.Errorf("making client: %v", err) |
| 53 |
} |
| 54 |
return &harness{closer: func() {}, client: client, numTopics: 0, numSubs: 0}, nil |
| 55 |
} |
| 56 |
|
| 57 |
func (h *harness) CreateTopic(ctx context.Context, testName string) (dt driver.Topic, cleanup func(), err error) { |
| 58 |
topicName := fmt.Sprintf("%s-topic-%d", sanitize(testName), atomic.AddUint32(&h.numTopics, 1)) |
| 59 |
return createTopic(ctx, h.client, topicName) |
| 60 |
} |
| 61 |
|
| 62 |
func topicPath(topicName string) string { |
| 63 |
return fmt.Sprintf("projects/%s/topics/%s", projectID, topicName) |
| 64 |
} |
| 65 |
func subscriptionPath(subName string) string { |
| 66 |
return fmt.Sprintf("projects/%s/subscriptions/%s", projectID, subName) |
| 67 |
} |
| 68 |
|
| 69 |
func createTopic(ctx context.Context, client *raw.Client, topicName string) (dt driver.Topic, cleanup func(), err error) { |
| 70 |
_, err = client.TopicAdminClient.CreateTopic(ctx, &pubsubpb.Topic{Name: topicPath(topicName)}) |
| 71 |
// We may encounter topics that were created by a previous test run and were |
| 72 |
// not properly cleaned up. In such a case delete the existing topic and create |
| 73 |
// a new topic with a higher topic number (to avoid cool-off issues between |
| 74 |
// deletion and re-creation). |
| 75 |
if err != nil && status.Code(err) == codes.AlreadyExists { |
| 76 |
deleteTopic(ctx, client, topicName) |
| 77 |
return createTopic(ctx, client, topicName) |
| 78 |
} |
| 79 |
if err != nil { |
| 80 |
return nil, nil, fmt.Errorf("failed to create topic: %w", err) |
| 81 |
} |
| 82 |
dt = openTopic(client.Publisher(topicName)) |
| 83 |
cleanup = func() { |
| 84 |
deleteTopic(ctx, client, topicName) |
| 85 |
} |
| 86 |
return dt, cleanup, nil |
| 87 |
} |
| 88 |
|
| 89 |
func deleteTopic(ctx context.Context, client *raw.Client, topicName string) { |
| 90 |
_ = client.TopicAdminClient.DeleteTopic(ctx, &pubsubpb.DeleteTopicRequest{ |
| 91 |
Topic: topicPath(topicName), |
| 92 |
}) |
| 93 |
} |
| 94 |
|
| 95 |
func (h *harness) MakeNonexistentTopic(ctx context.Context) (driver.Topic, error) { |
| 96 |
return openTopic(h.client.Publisher("nonexistent-topic")), nil |
| 97 |
} |
| 98 |
|
| 99 |
func (h *harness) CreateSubscription(ctx context.Context, dt driver.Topic, testName string) (ds driver.Subscription, cleanup func(), err error) { |
| 100 |
subName := fmt.Sprintf("%s-subscription-%d", sanitize(testName), atomic.AddUint32(&h.numSubs, 1)) |
| 101 |
return createSubscription(ctx, h.client, dt, subName) |
| 102 |
} |
| 103 |
|
| 104 |
func createSubscription(ctx context.Context, client *raw.Client, dt driver.Topic, subName string) (ds driver.Subscription, cleanup func(), err error) { |
| 105 |
t := dt.(*topic) |
| 106 |
_, err = client.SubscriptionAdminClient.CreateSubscription(ctx, &pubsubpb.Subscription{ |
| 107 |
Name: subscriptionPath(subName), |
| 108 |
Topic: t.publisher.String(), |
| 109 |
}) |
| 110 |
// We may encounter subscriptions that were created by a previous test run |
| 111 |
// and were not properly cleaned up. In such a case delete the existing |
| 112 |
// subscription and create a new subscription with a higher subscription |
| 113 |
// number (to avoid cool-off issues between deletion and re-creation). |
| 114 |
if err != nil && status.Code(err) == codes.AlreadyExists { |
| 115 |
deleteSubscription(ctx, client, subName) |
| 116 |
return createSubscription(ctx, client, dt, subName) |
| 117 |
} |
| 118 |
if err != nil { |
| 119 |
return nil, nil, fmt.Errorf("failed to create subscription: %w", err) |
| 120 |
} |
| 121 |
ds = openSubscription(client.Subscriber(subName), nil) |
| 122 |
cleanup = func() { |
| 123 |
deleteSubscription(ctx, client, subName) |
| 124 |
} |
| 125 |
return ds, cleanup, nil |
| 126 |
} |
| 127 |
|
| 128 |
func deleteSubscription(ctx context.Context, client *raw.Client, subName string) { |
| 129 |
_ = client.SubscriptionAdminClient.DeleteSubscription(ctx, &pubsubpb.DeleteSubscriptionRequest{ |
| 130 |
Subscription: subscriptionPath(subName)}, |
| 131 |
) |
| 132 |
} |
| 133 |
|
| 134 |
func (h *harness) MakeNonexistentSubscription(ctx context.Context) (driver.Subscription, func(), error) { |
| 135 |
return openSubscription(h.client.Subscriber("nonexistent-subscription"), nil), func() {}, nil |
| 136 |
} |
| 137 |
|
| 138 |
func (h *harness) Close() { |
| 139 |
h.client.Close() |
| 140 |
h.closer() |
| 141 |
} |
| 142 |
|
| 143 |
func (h *harness) MaxBatchSizes() (int, int) { |
| 144 |
return sendBatcherOpts.MaxBatchSize, ackBatcherOpts.MaxBatchSize |
| 145 |
} |
| 146 |
|
| 147 |
func (*harness) SupportsMultipleSubscriptions() bool { return true } |
| 148 |
|
| 149 |
func TestConformance(t *testing.T) { |
| 150 |
if !*setup.Record { |
| 151 |
t.Skip("replaying is not supported for gcppubsubv2 because it uses a streaming RPC internally") |
| 152 |
} |
| 153 |
asTests := []drivertest.AsTest{gcpAsTest{}} |
| 154 |
drivertest.RunConformanceTests(t, newHarness, asTests) |
| 155 |
} |
| 156 |
|
| 157 |
func BenchmarkGcpPubSub(b *testing.B) { |
| 158 |
ctx := context.Background() |
| 159 |
creds, err := gcp.DefaultCredentials(ctx) |
| 160 |
if err != nil { |
| 161 |
b.Fatal(err) |
| 162 |
} |
| 163 |
|
| 164 |
// Connect. |
| 165 |
conn, cleanup, err := Dial(ctx, gcp.CredentialsTokenSource(creds)) |
| 166 |
if err != nil { |
| 167 |
b.Fatal(err) |
| 168 |
} |
| 169 |
defer cleanup() |
| 170 |
|
| 171 |
// Make topic. |
| 172 |
client, err := Client(ctx, projectID, conn) |
| 173 |
if err != nil { |
| 174 |
b.Fatal(err) |
| 175 |
} |
| 176 |
topicName := fmt.Sprintf("%s-topic", b.Name()) |
| 177 |
dt, cleanup1, err := createTopic(ctx, client, topicName) |
| 178 |
if err != nil { |
| 179 |
b.Fatal(err) |
| 180 |
} |
| 181 |
defer cleanup1() |
| 182 |
topic := pubsub.NewTopic(dt, nil) |
| 183 |
defer topic.Shutdown(ctx) |
| 184 |
|
| 185 |
// Make subscription. |
| 186 |
subName := fmt.Sprintf("%s-subscription", b.Name()) |
| 187 |
ds, cleanup2, err := createSubscription(ctx, client, dt, subName) |
| 188 |
if err != nil { |
| 189 |
b.Fatal(err) |
| 190 |
} |
| 191 |
defer cleanup2() |
| 192 |
sub := pubsub.NewSubscription(ds, defaultRecvBatcherOpts, ackBatcherOpts) |
| 193 |
defer sub.Shutdown(ctx) |
| 194 |
|
| 195 |
drivertest.RunBenchmarks(b, topic, sub) |
| 196 |
} |
| 197 |
|
| 198 |
type gcpAsTest struct{} |
| 199 |
|
| 200 |
func (gcpAsTest) Name() string { |
| 201 |
return "gcp test" |
| 202 |
} |
| 203 |
|
| 204 |
func (gcpAsTest) TopicCheck(topic *pubsub.Topic) error { |
| 205 |
var c2 raw.Publisher |
| 206 |
if topic.As(&c2) { |
| 207 |
return fmt.Errorf("cast succeeded for %T, want failure", &c2) |
| 208 |
} |
| 209 |
var c3 *raw.Publisher |
| 210 |
if !topic.As(&c3) { |
| 211 |
return fmt.Errorf("cast failed for %T", &c3) |
| 212 |
} |
| 213 |
return nil |
| 214 |
} |
| 215 |
|
| 216 |
func (gcpAsTest) SubscriptionCheck(sub *pubsub.Subscription) error { |
| 217 |
var c2 raw.Subscriber |
| 218 |
if sub.As(&c2) { |
| 219 |
return fmt.Errorf("cast succeeded for %T, want failure", &c2) |
| 220 |
} |
| 221 |
var c3 *raw.Subscriber |
| 222 |
if !sub.As(&c3) { |
| 223 |
return fmt.Errorf("cast failed for %T", &c3) |
| 224 |
} |
| 225 |
return nil |
| 226 |
} |
| 227 |
|
| 228 |
func (gcpAsTest) TopicErrorCheck(t *pubsub.Topic, err error) error { |
| 229 |
var s *status.Status |
| 230 |
if !t.ErrorAs(err, &s) { |
| 231 |
return fmt.Errorf("failed to convert %v (%T) to a gRPC Status", err, err) |
| 232 |
} |
| 233 |
if s.Code() != codes.NotFound { |
| 234 |
return fmt.Errorf("got code %s, want NotFound", s.Code()) |
| 235 |
} |
| 236 |
return nil |
| 237 |
} |
| 238 |
|
| 239 |
func (gcpAsTest) SubscriptionErrorCheck(sub *pubsub.Subscription, err error) error { |
| 240 |
var s *status.Status |
| 241 |
if !sub.ErrorAs(err, &s) { |
| 242 |
return fmt.Errorf("failed to convert %v (%T) to a gRPC Status", err, err) |
| 243 |
} |
| 244 |
if s.Code() != codes.NotFound { |
| 245 |
return fmt.Errorf("got code %s, want NotFound", s.Code()) |
| 246 |
} |
| 247 |
return nil |
| 248 |
} |
| 249 |
|
| 250 |
func (gcpAsTest) MessageCheck(m *pubsub.Message) error { |
| 251 |
var rm raw.Message |
| 252 |
if m.As(&rm) { |
| 253 |
return fmt.Errorf("cast succeeded for %T, want failure", &rm) |
| 254 |
} |
| 255 |
var prm *raw.Message |
| 256 |
if !m.As(&prm) { |
| 257 |
return fmt.Errorf("cast failed for %T", &prm) |
| 258 |
} |
| 259 |
return nil |
| 260 |
} |
| 261 |
|
| 262 |
func (gcpAsTest) BeforeSend(as func(any) bool) error { |
| 263 |
var prm *raw.Message |
| 264 |
if !as(&prm) { |
| 265 |
return fmt.Errorf("cast failed for %T", &prm) |
| 266 |
} |
| 267 |
return nil |
| 268 |
} |
| 269 |
|
| 270 |
func (gcpAsTest) AfterSend(as func(any) bool) error { |
| 271 |
var msgId string |
| 272 |
if !as(&msgId) { |
| 273 |
return fmt.Errorf("cast failed for %T", &msgId) |
| 274 |
} |
| 275 |
return nil |
| 276 |
} |
| 277 |
|
| 278 |
func sanitize(testName string) string { |
| 279 |
return strings.Replace(testName, "/", "_", -1) |
| 280 |
} |
| 281 |
|
| 282 |
func TestOpenTopic(t *testing.T) { |
| 283 |
ctx := context.Background() |
| 284 |
creds, err := setup.FakeGCPCredentials(ctx) |
| 285 |
if err != nil { |
| 286 |
t.Fatal(err) |
| 287 |
} |
| 288 |
projID, err := gcp.DefaultProjectID(creds) |
| 289 |
if err != nil { |
| 290 |
t.Fatal(err) |
| 291 |
} |
| 292 |
conn, cleanup, err := Dial(ctx, gcp.CredentialsTokenSource(creds)) |
| 293 |
if err != nil { |
| 294 |
t.Fatal(err) |
| 295 |
} |
| 296 |
defer cleanup() |
| 297 |
client, err := Client(ctx, projID, conn) |
| 298 |
if err != nil { |
| 299 |
t.Fatal(err) |
| 300 |
} |
| 301 |
topic := OpenTopic(client, "my-topic", nil) |
| 302 |
defer topic.Shutdown(ctx) |
| 303 |
err = topic.Send(ctx, &pubsub.Message{Body: []byte("hello world")}) |
| 304 |
if err == nil { |
| 305 |
t.Error("got nil, want error") |
| 306 |
} |
| 307 |
|
| 308 |
// Repeat with OpenTopicByPath. |
| 309 |
topic, err = OpenTopicByPath(client, path.Join("projects", string(projID), "topics", "my-topic"), nil) |
| 310 |
if err != nil { |
| 311 |
t.Fatal(err) |
| 312 |
} |
| 313 |
defer topic.Shutdown(ctx) |
| 314 |
err = topic.Send(ctx, &pubsub.Message{Body: []byte("hello world")}) |
| 315 |
if err == nil { |
| 316 |
t.Error("got nil, want error") |
| 317 |
} |
| 318 |
|
| 319 |
// Try an invalid path. |
| 320 |
_, err = OpenTopicByPath(client, "my-topic", nil) |
| 321 |
if err == nil { |
| 322 |
t.Error("got nil, want error") |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
func TestOpenSubscription(t *testing.T) { |
| 327 |
ctx := context.Background() |
| 328 |
creds, err := setup.FakeGCPCredentials(ctx) |
| 329 |
if err != nil { |
| 330 |
t.Fatal(err) |
| 331 |
} |
| 332 |
projID, err := gcp.DefaultProjectID(creds) |
| 333 |
if err != nil { |
| 334 |
t.Fatal(err) |
| 335 |
} |
| 336 |
conn, cleanup, err := Dial(ctx, gcp.CredentialsTokenSource(creds)) |
| 337 |
if err != nil { |
| 338 |
t.Fatal(err) |
| 339 |
} |
| 340 |
defer cleanup() |
| 341 |
client, err := Client(ctx, projID, conn) |
| 342 |
if err != nil { |
| 343 |
t.Fatal(err) |
| 344 |
} |
| 345 |
sub := OpenSubscription(client, "my-subscription", nil) |
| 346 |
defer sub.Shutdown(ctx) |
| 347 |
_, err = sub.Receive(ctx) |
| 348 |
if err == nil { |
| 349 |
t.Error("got nil, want error") |
| 350 |
} |
| 351 |
|
| 352 |
// Repeat with OpenSubscriptionByPath. |
| 353 |
sub, err = OpenSubscriptionByPath(client, path.Join("projects", string(projID), "subscriptions", "my-subscription"), nil) |
| 354 |
if err != nil { |
| 355 |
t.Fatal(err) |
| 356 |
} |
| 357 |
defer sub.Shutdown(ctx) |
| 358 |
_, err = sub.Receive(ctx) |
| 359 |
if err == nil { |
| 360 |
t.Error("got nil, want error") |
| 361 |
} |
| 362 |
|
| 363 |
// Try an invalid path. |
| 364 |
_, err = OpenSubscriptionByPath(client, "my-subscription", nil) |
| 365 |
if err == nil { |
| 366 |
t.Error("got nil, want error") |
| 367 |
} |
| 368 |
} |
| 369 |
|
| 370 |
func TestOpenTopicFromURL(t *testing.T) { |
| 371 |
cleanup := setup.FakeGCPDefaultCredentials(t) |
| 372 |
defer cleanup() |
| 373 |
|
| 374 |
tests := []struct { |
| 375 |
URL string |
| 376 |
WantErr bool |
| 377 |
}{ |
| 378 |
// OK, short form. |
| 379 |
{"gcppubsubv2://myproject/mytopic", false}, |
| 380 |
// OK, long form. |
| 381 |
{"gcppubsubv2://projects/myproject/topic/mytopic", false}, |
| 382 |
// Invalid parameter. |
| 383 |
{"gcppubsubv2://myproject/mytopic?param=value", true}, |
| 384 |
// Valid max_send_batch_size |
| 385 |
{"gcppubsubv2://projects/mytopic?max_send_batch_size=1", false}, |
| 386 |
// Invalid max_send_batch_size |
| 387 |
{"gcppubsubv2://projects/mytopic?max_send_batch_size=0", true}, |
| 388 |
// Invalid max_send_batch_size |
| 389 |
{"gcppubsubv2://projects/mytopic?max_send_batch_size=1001", true}, |
| 390 |
} |
| 391 |
|
| 392 |
ctx := context.Background() |
| 393 |
for _, test := range tests { |
| 394 |
topic, err := pubsub.OpenTopic(ctx, test.URL) |
| 395 |
if (err != nil) != test.WantErr { |
| 396 |
t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr) |
| 397 |
} |
| 398 |
if topic != nil { |
| 399 |
topic.Shutdown(ctx) |
| 400 |
} |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
func TestOpenSubscriptionFromURL(t *testing.T) { |
| 405 |
cleanup := setup.FakeGCPDefaultCredentials(t) |
| 406 |
defer cleanup() |
| 407 |
|
| 408 |
tests := []struct { |
| 409 |
URL string |
| 410 |
WantErr bool |
| 411 |
}{ |
| 412 |
// OK, short form. |
| 413 |
{"gcppubsubv2://myproject/mysub", false}, |
| 414 |
// OK, long form. |
| 415 |
{"gcppubsubv2://projects/myproject/subscriptions/mysub", false}, |
| 416 |
// Invalid parameter. |
| 417 |
{"gcppubsubv2://myproject/mysub?param=value", true}, |
| 418 |
// Valid max_recv_batch_size |
| 419 |
{"gcppubsubv2://projects/myproject/subscriptions/mysub?max_recv_batch_size=1", false}, |
| 420 |
// Invalid max_recv_batch_size |
| 421 |
{"gcppubsubv2://projects/myproject/subscriptions/mysub?max_recv_batch_size=0", true}, |
| 422 |
// Invalid max_recv_batch_size |
| 423 |
{"gcppubsubv2://projects/myproject/subscriptions/mysub?max_recv_batch_size=1001", true}, |
| 424 |
} |
| 425 |
|
| 426 |
ctx := context.Background() |
| 427 |
for _, test := range tests { |
| 428 |
sub, err := pubsub.OpenSubscription(ctx, test.URL) |
| 429 |
if (err != nil) != test.WantErr { |
| 430 |
t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr) |
| 431 |
} |
| 432 |
if sub != nil { |
| 433 |
sub.Shutdown(ctx) |
| 434 |
} |
| 435 |
} |
| 436 |
} |