def pick_coding()

in http/get_compressed/python/server/server.py [0:0]


def pick_coding(accept_encoding_header, available):
    """
    Pick the content-coding according to the Accept-Encoding header.

    This is used when using HTTP response compression instead of IPC buffer
    compression.

    Parameters
    ----------
    accept_encoding_header : str
        The value of the Accept-Encoding header from an HTTP request.
    available : list of str
        The content-codings that the server can provide in the order preferred
        by the server. Example: ["zstd", "br", "gzip"].

    Returns
    -------
    str
        The content-coding that the server should use to compress the response.
        "identity" is returned if no acceptable content-coding is found in the
        list of available codings.

        None if the client does not accept any of the available content-codings
        and doesn't accept "identity" (uncompressed) either. In this case,
        a "406 Not Acceptable" response should be sent.
    """
    accepted = parse_header_value("Accept-Encoding", accept_encoding_header)

    def qvalue_or(params, default):
        qvalue = params.get("q")
        if qvalue is not None:
            try:
                return float(qvalue)
            except ValueError:
                raise ValueError(f"Invalid qvalue in Accept-Encoding header: {qvalue}")
        return default

    if "identity" not in available:
        available = available + ["identity"]
    state = {}
    for coding, params in accepted:
        qvalue = qvalue_or(params, 0.0001 if coding == "identity" else 1.0)
        if coding == "*":
            for coding in available:
                if coding not in state:
                    state[coding] = qvalue
        elif coding in available:
            state[coding] = qvalue
    # "identity" is always acceptable unless explicitly refused (;q=0)
    if "identity" not in state:
        state["identity"] = 0.0001
    # all the candidate codings are now in the state dictionary and we
    # have to consider only the ones that have the maximum qvalue
    max_qvalue = max(state.values())
    if max_qvalue == 0.0:
        return None
    for coding in available:
        if coding in state and state[coding] == max_qvalue:
            return coding
    return None