internal/cloud: do not use canceled context in rate limiter

When errgroup is used in the rate limiter, a canceled context is
passed to the next method in the interceptor. A context is canceled
once the Wait() method returns. This change uses the same context
throughout the method instead of creating a new one just for the
errgroup.

For golang/go#40950

Change-Id: I64462394298a6b849187c288e5f76e92630572f9
Reviewed-on: https://go-review.googlesource.com/c/build/+/268697
Trust: Carlos Amedee <carlos@golang.org>
Run-TryBot: Carlos Amedee <carlos@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
Reviewed-by: Alexander Rakoczy <alex@golang.org>
diff --git a/internal/cloud/aws_interceptor.go b/internal/cloud/aws_interceptor.go
index d3f9763..4b2b415 100644
--- a/internal/cloud/aws_interceptor.go
+++ b/internal/cloud/aws_interceptor.go
@@ -111,7 +111,7 @@
 
 // RunInstancesWithContext rate limits calls. The rate limiter will return an error if the request exceeds the bucket size, the Context is canceled, or the expected wait time exceeds the Context's Deadline. An error is returned if either the rate or resource limiter returns an error.
 func (i *EC2RateLimitInterceptor) RunInstancesWithContext(ctx context.Context, in *ec2.RunInstancesInput, opts ...request.Option) (*ec2.Reservation, error) {
-	g, ctx := errgroup.WithContext(ctx)
+	g := new(errgroup.Group)
 	g.Go(func() error {
 		return i.runInstancesRate.Wait(ctx)
 	})
@@ -131,7 +131,7 @@
 
 // TerminateInstancesWithContext rate limits calls. The rate limiter will return an error if the request exceeds the bucket size, the Context is canceled, or the expected wait time exceeds the Context's Deadline. An error is returned if either the rate or resource limiter returns an error.
 func (i *EC2RateLimitInterceptor) TerminateInstancesWithContext(ctx context.Context, in *ec2.TerminateInstancesInput, opts ...request.Option) (*ec2.TerminateInstancesOutput, error) {
-	g, ctx := errgroup.WithContext(ctx)
+	g := new(errgroup.Group)
 	g.Go(func() error {
 		return i.mutatingRate.Wait(ctx)
 	})
diff --git a/internal/cloud/aws_interceptor_test.go b/internal/cloud/aws_interceptor_test.go
index d77aceb..ddd0987 100644
--- a/internal/cloud/aws_interceptor_test.go
+++ b/internal/cloud/aws_interceptor_test.go
@@ -69,6 +69,9 @@
 	if ctx == nil || input == nil || len(opts) != 1 {
 		f.t.Fatal("RunInstancesWithContext params not passed down")
 	}
+	if ctx.Err() != nil {
+		f.t.Fatalf("context.Err() = %s; want no error", ctx.Err())
+	}
 	return nil, nil
 }
 
@@ -76,6 +79,9 @@
 	if ctx == nil || input == nil || len(opts) != 1 {
 		f.t.Fatal("TerminateInstancesWithContext params not passed down")
 	}
+	if ctx.Err() != nil {
+		f.t.Fatalf("context.Err() = %s; want no error", ctx.Err())
+	}
 	return nil, nil
 }