init takes care of actually establishing the connection to the gRPC server. If the connection is already established, this is a no-op. This function is go-routine safe, because potentially multiple callers could access this at the same time.
()
| 125 | // this is a no-op. This function is go-routine safe, because potentially multiple callers could access this at the same |
| 126 | // time. |
| 127 | func (conn *RPCConnection[T]) init() (err error) { |
| 128 | if conn == nil { |
| 129 | return errors.New("RPC connection not configured") |
| 130 | } |
| 131 | |
| 132 | // Check, if we already have a valid client connection. We use a read-only lock for a faster access. |
| 133 | conn.m.RLock() |
| 134 | if conn.cc != nil && conn.cc.GetState() != connectivity.Shutdown { |
| 135 | defer conn.m.RUnlock() |
| 136 | return nil |
| 137 | } |
| 138 | |
| 139 | // If we arrive at this point we need to exchange our read-only lock for a write lock, since we are creating a new |
| 140 | // connection and will write to the client conn property. |
| 141 | conn.m.RUnlock() |
| 142 | conn.m.Lock() |
| 143 | defer conn.m.Unlock() |
| 144 | |
| 145 | // Establish a connection to the specified gRPC service |
| 146 | conn.cc, err = grpc.NewClient(conn.Target, |
| 147 | DefaultGrpcDialOptions(conn.Target, conn, conn.Opts...)..., |
| 148 | ) |
| 149 | if err != nil { |
| 150 | return fmt.Errorf("could not connect to gPRC target %q: %w", conn.Target, err) |
| 151 | } |
| 152 | |
| 153 | return nil |
| 154 | } |
no test coverage detected