<commit_before>class Api::CompactIndexController < Api::BaseController
  before_action :find_rubygem_by_name, only: [:info]

  def names
    names = GemInfo.ordered_names
    render_range CompactIndex.names(names)
  end

  def versions
    versions_path = Rails.application.config.rubygems['versions_file_location']
    versions_file = CompactIndex::VersionsFile.new(versions_path)
    from_date = versions_file.updated_at
    extra_gems = GemInfo.compact_index_versions(from_date)
    render_range CompactIndex.versions(versions_file, extra_gems)
  end

  def info
    return unless stale?(@rubygem)
    info_params = GemInfo.new(@rubygem.name).compact_index_info
    render_range CompactIndex.info(info_params)
  end

  private

  def render_range(response_body)
    headers['ETag'] = '"' << Digest::MD5.hexdigest(response_body) << '"'

    ranges = Rack::Utils.byte_ranges(env, response_body.bytesize)
    if ranges
      ranged_response = ranges.map { |range| response_body.byteslice(range) }.join
      render status: 206, plain: ranged_response
    else
      render status: 200, plain: response_body
    end
  end<commit_msg>add cache headers for compact index<commit_after>class Api::CompactIndexController < Api::BaseController
  before_action :find_rubygem_by_name, only: [:info]
  before_action :set_compact_index_cache_headers

  def names
    names = GemInfo.ordered_names
    render_range CompactIndex.names(names)
  end

  def versions
    versions_path = Rails.application.config.rubygems['versions_file_location']
    versions_file = CompactIndex::VersionsFile.new(versions_path)
    from_date = versions_file.updated_at
    extra_gems = GemInfo.compact_index_versions(from_date)
    render_range CompactIndex.versions(versions_file, extra_gems)
  end

  def info
    return unless stale?(@rubygem)
    info_params = GemInfo.new(@rubygem.name).compact_index_info
    render_range CompactIndex.info(info_params)
  end

  private

  def set_compact_index_cache_headers
    expires_in 60, public: true
    fastly_expires_in 3600
  end

  def render_range(response_body)
    headers['ETag'] = '"' << Digest::MD5.hexdigest(response_body) << '"'

    ranges = Rack::Utils.byte_ranges(env, response_body.bytesize)
    if ranges
      ranged_response = ranges.map { |range| response_body.byteslice(range) }.join
      render status: 206, plain: ranged_response
    else
      render status: 200, plain: response_body
    end
  end
{'fraction_non_alphanumeric': 0.08569085690856909, 'fraction_numerical': 0.008200082000820008, 'mean_word_length': 4.570776255707763, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3009965', 'n_tokens_mistral': 816, 'n_tokens_neox': 773, 'n_words': 147}