service.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. *
  3. * Copyright 2021 Google LLC
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * https://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. // Package service is a utility for calling the S2A handshaker service.
  19. package service
  20. import (
  21. "context"
  22. "sync"
  23. grpc "google.golang.org/grpc"
  24. "google.golang.org/grpc/credentials"
  25. "google.golang.org/grpc/credentials/insecure"
  26. )
  27. var (
  28. // mu guards hsConnMap and hsDialer.
  29. mu sync.Mutex
  30. // hsConnMap represents a mapping from an S2A handshaker service address
  31. // to a corresponding connection to an S2A handshaker service instance.
  32. hsConnMap = make(map[string]*grpc.ClientConn)
  33. // hsDialer will be reassigned in tests.
  34. hsDialer = grpc.DialContext
  35. )
  36. // Dial dials the S2A handshaker service. If a connection has already been
  37. // established, this function returns it. Otherwise, a new connection is
  38. // created.
  39. func Dial(ctx context.Context, handshakerServiceAddress string, transportCreds credentials.TransportCredentials) (*grpc.ClientConn, error) {
  40. mu.Lock()
  41. defer mu.Unlock()
  42. hsConn, ok := hsConnMap[handshakerServiceAddress]
  43. if !ok {
  44. // Create a new connection to the S2A handshaker service. Note that
  45. // this connection stays open until the application is closed.
  46. var grpcOpts []grpc.DialOption
  47. if transportCreds != nil {
  48. grpcOpts = append(grpcOpts, grpc.WithTransportCredentials(transportCreds))
  49. } else {
  50. grpcOpts = append(grpcOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
  51. }
  52. var err error
  53. hsConn, err = hsDialer(ctx, handshakerServiceAddress, grpcOpts...)
  54. if err != nil {
  55. return nil, err
  56. }
  57. hsConnMap[handshakerServiceAddress] = hsConn
  58. }
  59. return hsConn, nil
  60. }