-
Notifications
You must be signed in to change notification settings - Fork 1.5k
feat(pubsub/v2): add subscriber shutdown options #12829
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
hongalex
merged 13 commits into
googleapis:main
from
hongalex:feat-pubsub-shutdown-options
Sep 25, 2025
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
282d662
add initial settings
hongalex 3f85207
feat(pubsub/v2): add subscriber shutdown options
hongalex bfe941a
add log printf statement back
hongalex 6f242bf
propagate stream errors to Receive
hongalex 16d03f0
fix error with channel closing
hongalex f655232
simplify stream pulling channels
hongalex 1a9e6de
revert recent changes
hongalex 95bed53
fix default options pointer bug, shorten tests
hongalex 345ae1a
revert unrelated changes to existing tests
hongalex a186fbd
fix race in CancelReceive test
hongalex 7b17c9f
make comments more clear
hongalex 779eb20
added warning to Timeout default
hongalex 6097da0
add better clarifying comments to shutdown behavior
hongalex File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| // Copyright 2025 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. | ||
|
|
||
| package pubsub | ||
|
|
||
| import "time" | ||
|
|
||
| // ShutdownOptions configures the shutdown behavior of the subscriber. | ||
| // When ShutdownOptions is nil, the client library will | ||
| // assume disabled/infinite timeout. | ||
| // | ||
| // Warning: The interaction between Timeout and Behavior might be surprising. | ||
| // Read about the interaction of these below to ensure you | ||
| // get the desired behavior. | ||
| type ShutdownOptions struct { | ||
| // Timeout specifies the time the subscriber should wait | ||
| // before forcefully shutting down.. | ||
| // In ShutdownBehaviorNackImmediately mode, this configures the timeout | ||
| // for message nacks before shutting down. | ||
| // | ||
| // Set to zero to immediately shutdown. | ||
| // Set to a negative value to disable timeout. | ||
| // Both zero and negative values overrides the ShutdownBehavior. | ||
| Timeout time.Duration | ||
|
|
||
| // Behavior defines the strategy the subscriber should use when | ||
| // shutting down (wait or nack messages). | ||
| // When ShutdownOptions is set, but Timeout is unspecified, the default zero-value | ||
| // will result in immediate shutdown. When needing a specific a behavior, | ||
| // always set a non-zero Timeout. | ||
| Behavior ShutdownBehavior | ||
| } | ||
|
|
||
| // ShutdownBehavior defines the strategy the subscriber should take when | ||
| // shutting down. Current options are graceful shutdown vs nacking messages. | ||
| type ShutdownBehavior int | ||
|
|
||
| const ( | ||
| // ShutdownBehaviorWaitForProcessing means the subscriber client will wait for | ||
| // outstanding messages to be processed. | ||
| ShutdownBehaviorWaitForProcessing = iota | ||
|
hongalex marked this conversation as resolved.
|
||
|
|
||
| // ShutdownBehaviorNackImmediately means the subscriber client will nack all | ||
| // outstanding messages before closing. | ||
| ShutdownBehaviorNackImmediately | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| // Copyright 2025 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. | ||
|
|
||
| package pubsub | ||
|
|
||
| import ( | ||
| "context" | ||
| "sync" | ||
| "testing" | ||
| "time" | ||
|
|
||
| pb "cloud.google.com/go/pubsub/v2/apiv1/pubsubpb" | ||
| ) | ||
|
|
||
| func TestShutdown_NackImmediately(t *testing.T) { | ||
| t.Parallel() | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| defer cancel() | ||
| client, srv := newFake(t) | ||
| defer client.Close() | ||
| defer srv.Close() | ||
|
|
||
| topic := mustCreateTopic(t, client, "projects/p/topics/t") | ||
| sub := mustCreateSubConfig(t, client, &pb.Subscription{ | ||
| Name: "projects/p/subscriptions/s", | ||
| Topic: topic.String(), | ||
| }) | ||
|
|
||
| // Part of this test: pretend to extend the min duration quite a bit so we can test | ||
| // if the message has been properly nacked. | ||
| sub.ReceiveSettings.MinDurationPerAckExtension = 10 * time.Minute | ||
| sub.ReceiveSettings.ShutdownOptions = &ShutdownOptions{ | ||
| Behavior: ShutdownBehaviorNackImmediately, | ||
| Timeout: 1 * time.Minute, | ||
| } | ||
| var wg sync.WaitGroup | ||
| wg.Add(1) | ||
| go func() { | ||
| defer wg.Done() | ||
| _, err := topic.Publish(ctx, &Message{Data: []byte("m1")}).Get(ctx) | ||
| if err != nil { | ||
| t.Errorf("Publish().Get() got err: %v", err) | ||
| } | ||
| }() | ||
| wg.Wait() | ||
|
|
||
| cctx, ccancel := context.WithCancel(ctx) | ||
| go sub.Receive(cctx, func(ctx context.Context, m *Message) { | ||
| // First time receiving, cancel the context to trigger shutdown. | ||
| // Don't cancel away to avoid race condition with fake. | ||
| time.AfterFunc(2*time.Second, ccancel) | ||
| }) | ||
|
|
||
| // Wait for the message to be redelivered. | ||
| time.Sleep(5 * time.Second) | ||
|
|
||
| var received int | ||
| var receiveLock sync.Mutex | ||
| ctx2, cancel := context.WithTimeout(ctx, 30*time.Second) | ||
| err := sub.Receive(ctx2, func(ctx context.Context, m *Message) { | ||
| receiveLock.Lock() | ||
| defer receiveLock.Unlock() | ||
| received++ | ||
| m.Ack() | ||
| cancel() | ||
| }) | ||
| if err != nil { | ||
| t.Errorf("got err from recv: %v", err) | ||
| } | ||
| if received != 1 { | ||
| t.Errorf("expected 1 delivery, got %d", received) | ||
| } | ||
| } | ||
|
|
||
| func TestShutdown_WaitForProcessing(t *testing.T) { | ||
| t.Parallel() | ||
| tests := []struct { | ||
| name string | ||
| shutdownTimeout time.Duration | ||
| expectedTimeout time.Duration | ||
| minTime time.Duration | ||
| }{ | ||
| { | ||
| name: "BailImmediately", | ||
| shutdownTimeout: 0 * time.Second, | ||
| expectedTimeout: 5 * time.Second, | ||
| }, | ||
| { | ||
| name: "WithTimeout", | ||
| shutdownTimeout: 5 * time.Second, | ||
| expectedTimeout: 6 * time.Second, | ||
| minTime: 4 * time.Second, | ||
| }, | ||
| } | ||
|
|
||
| for _, tc := range tests { | ||
| t.Run(tc.name, func(t *testing.T) { | ||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| defer cancel() | ||
| client, srv := newFake(t) | ||
| defer client.Close() | ||
| defer srv.Close() | ||
|
|
||
| topic := mustCreateTopic(t, client, "projects/p/topics/t") | ||
| sub := mustCreateSubConfig(t, client, &pb.Subscription{ | ||
| Name: "projects/p/subscriptions/s", | ||
| Topic: topic.String(), | ||
| }) | ||
| sub.ReceiveSettings.ShutdownOptions = &ShutdownOptions{ | ||
| Behavior: ShutdownBehaviorWaitForProcessing, | ||
| Timeout: tc.shutdownTimeout, | ||
| } | ||
| processingTime := 1 * time.Hour | ||
|
|
||
| var wg sync.WaitGroup | ||
| wg.Add(1) | ||
| go func() { | ||
| defer wg.Done() | ||
| _, err := topic.Publish(ctx, &Message{Data: []byte("m1")}).Get(ctx) | ||
| if err != nil { | ||
| t.Errorf("Publish().Get() got err: %v", err) | ||
| } | ||
| }() | ||
| wg.Wait() | ||
|
|
||
| cctx, cancel2 := context.WithCancel(ctx) | ||
| defer cancel2() | ||
| start := time.Now() | ||
| sub.Receive(cctx, func(ctx context.Context, m *Message) { | ||
| cancel() | ||
| // Simulate a long processing message that we want to cancel right away. | ||
| // The message should never be acked since we expect the client to bail early. | ||
| time.Sleep(processingTime) | ||
| m.Ack() | ||
| }) | ||
|
|
||
| elapsed := time.Since(start) | ||
| if elapsed > tc.expectedTimeout { | ||
| t.Errorf("expected quick cancellation, elapsed: %v, want less than: %v", elapsed, tc.expectedTimeout) | ||
| } | ||
| if tc.minTime > 0 && elapsed < tc.minTime { | ||
| t.Errorf("expected to wait for shutdown, elapsed: %v, want greater than: %v", elapsed, tc.minTime) | ||
| } | ||
| }) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.