1# Copyright 2017 Google LLC
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#     http://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"""Helpers for making API requests via gapic / gRPC."""
16
17from grpc import insecure_channel
18from urllib.parse import urlparse
19
20from google.cloud._helpers import make_secure_channel
21from google.cloud._http import DEFAULT_USER_AGENT
22from google.cloud.datastore_v1.services.datastore import client as datastore_client
23from google.cloud.datastore_v1.services.datastore.transports import grpc
24
25
26def make_datastore_api(client):
27    """Create an instance of the GAPIC Datastore API.
28
29    :type client: :class:`~google.cloud.datastore.client.Client`
30    :param client: The client that holds configuration details.
31
32    :rtype: :class:`.datastore.v1.datastore_client.DatastoreClient`
33    :returns: A datastore API instance with the proper credentials.
34    """
35    parse_result = urlparse(client._base_url)
36    host = parse_result.netloc
37    if parse_result.scheme == "https":
38        channel = make_secure_channel(client._credentials, DEFAULT_USER_AGENT, host)
39    else:
40        channel = insecure_channel(host)
41
42    transport = grpc.DatastoreGrpcTransport(channel=channel)
43    return datastore_client.DatastoreClient(
44        transport=transport, client_info=client._client_info
45    )
46