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 constructing routing headers. 
    16 
    17These headers are used by Google infrastructure to determine how to route 
    18requests, especially for services that are regional. 
    19 
    20Generally, these headers are specified as gRPC metadata. 
    21""" 
    22 
    23import functools 
    24from enum import Enum 
    25from urllib.parse import urlencode 
    26 
    27ROUTING_METADATA_KEY = "x-goog-request-params" 
    28# This is the value for the `maxsize` argument of @functools.lru_cache 
    29# https://docs.python.org/3/library/functools.html#functools.lru_cache 
    30# This represents the number of recent function calls to store. 
    31ROUTING_PARAM_CACHE_SIZE = 32 
    32 
    33 
    34def to_routing_header(params, qualified_enums=True): 
    35    """Returns a routing header string for the given request parameters. 
    36 
    37    Args: 
    38        params (Mapping[str, str | bytes | Enum]): A dictionary containing the request 
    39            parameters used for routing. 
    40        qualified_enums (bool): Whether to represent enum values 
    41            as their type-qualified symbol names instead of as their 
    42            unqualified symbol names. 
    43 
    44    Returns: 
    45        str: The routing header string. 
    46    """ 
    47    tuples = params.items() if isinstance(params, dict) else params 
    48    if not qualified_enums: 
    49        tuples = [(x[0], x[1].name) if isinstance(x[1], Enum) else x for x in tuples] 
    50    return "&".join([_urlencode_param(*t) for t in tuples]) 
    51 
    52 
    53def to_grpc_metadata(params, qualified_enums=True): 
    54    """Returns the gRPC metadata containing the routing headers for the given 
    55    request parameters. 
    56 
    57    Args: 
    58        params (Mapping[str, str | bytes | Enum]): A dictionary containing the request 
    59            parameters used for routing. 
    60        qualified_enums (bool): Whether to represent enum values 
    61            as their type-qualified symbol names instead of as their 
    62            unqualified symbol names. 
    63 
    64    Returns: 
    65        Tuple(str, str): The gRPC metadata containing the routing header key 
    66            and value. 
    67    """ 
    68    return (ROUTING_METADATA_KEY, to_routing_header(params, qualified_enums)) 
    69 
    70 
    71# use caching to avoid repeated computation 
    72@functools.lru_cache(maxsize=ROUTING_PARAM_CACHE_SIZE) 
    73def _urlencode_param(key, value): 
    74    """Cacheable wrapper over urlencode 
    75 
    76    Args: 
    77        key (str): The key of the parameter to encode. 
    78        value (str | bytes | Enum): The value of the parameter to encode. 
    79 
    80    Returns: 
    81        str: The encoded parameter. 
    82    """ 
    83    return urlencode( 
    84        {key: value}, 
    85        # Per Google API policy (go/api-url-encoding), / is not encoded. 
    86        safe="/", 
    87    )