class Aws::Plugins::EndpointDiscovery::Handler

def _apply_endpoint_discovery_user_agent(ctx)

def _apply_endpoint_discovery_user_agent(ctx)
  if ctx.config.user_agent_suffix.nil?
    ctx.config.user_agent_suffix = "endpoint-discovery"
  elsif !ctx.config.user_agent_suffix.include? "endpoint-discovery"
    ctx.config.user_agent_suffix += "endpoint-discovery"
  end
end

def _discover_endpoint(ctx, required)

def _discover_endpoint(ctx, required)
  cache = ctx.config.endpoint_cache
  key = cache.extract_key(ctx)
  if required
    unless ctx.config.endpoint_discovery
      raise ArgumentError, "Operation #{ctx.operation.name} requires "\
        'endpoint_discovery to be enabled.'
    end
    # required for the operation
    unless cache.key?(key)
      cache.update(key, ctx)
    end
    endpoint = cache[key]
    # hard fail if endpoint is not discovered
    raise Aws::Errors::EndpointDiscoveryError.new unless endpoint
    endpoint
  elsif ctx.config.endpoint_discovery
    # not required for the operation
    # but enabled
    if cache.key?(key)
      cache[key]
    elsif ctx.config.active_endpoint_cache
      # enabled active cache pull
      interval = ctx.config.endpoint_cache_poll_interval
      if key.include?('_')
        # identifier related, kill the previous polling thread by key
        # because endpoint req params might be changed
        cache.delete_polling_thread(key)
      end
      # start a thread for polling endpoints when non-exist
      unless cache.threads_key?(key)
        thread = Thread.new do
          while !cache.key?(key) do
            cache.update(key, ctx)
            sleep(interval)
          end
        end
        cache.update_polling_pool(key, thread)
      end
      cache[key]
    else
      # disabled active cache pull
      # attempt, buit fail soft
      cache.update(key, ctx)
      cache[key]
    end
  end
end

def _valid_uri(address)

def _valid_uri(address)
  # returned address can be missing scheme
  if address.start_with?('http')
    URI.parse(address)
  else
    URI.parse("https://" + address)
  end
end

def call(context)

def call(context)
  if context.operation.endpoint_operation
    context.http_request.headers['x-amz-api-version'] = context.config.api.version
    _apply_endpoint_discovery_user_agent(context)
  elsif discovery_cfg = context.operation.endpoint_discovery
    endpoint = _discover_endpoint(
      context,
      Aws::Util.str_2_bool(discovery_cfg["required"])
    )
    if endpoint
      context.http_request.endpoint = _valid_uri(endpoint.address)
      # Skips dynamic endpoint usage, use this endpoint instead
      context[:discovered_endpoint] = true
    end
    if endpoint || context.config.endpoint_discovery
      _apply_endpoint_discovery_user_agent(context)
    end
  end
  @handler.call(context)
end