diff --git a/.github/workflows/ensure-orgs.yml b/.github/workflows/ensure-orgs.yml index 87f6dc3f..a5113dbb 100644 --- a/.github/workflows/ensure-orgs.yml +++ b/.github/workflows/ensure-orgs.yml @@ -39,5 +39,6 @@ jobs: run: bundle exec ruby test/ensure_orgs_test.rb - name: Ensure data entries are GitHub Orgs env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ORG_BASE_REF: ${{ github.event.pull_request.base.sha || github.event.before }} run: bundle exec script/ensure-orgs diff --git a/script/ensure-orgs b/script/ensure-orgs index dd0f1948..b617f547 100755 --- a/script/ensure-orgs +++ b/script/ensure-orgs @@ -3,27 +3,12 @@ # Ensures that all organizations listed in _data are in fact, organizations # Set ORG_BASE_REF to check only names absent from that Git revision; omit it for a full scan. +# GITHUB_TOKEN must contain a GitHub API token when there are organizations to check. require 'typhoeus' -require 'parallel' require 'yaml' require 'open3' - -class Cache - def initialize - @memory = {} - end - - def get(request) - @memory[request] - end - - def set(request, response) - @memory[request] = response - end -end - -Typhoeus::Config.cache = Cache.new +require 'json' puts 'Checking that all orgs listed are in fact, an org...' @@ -48,29 +33,89 @@ def baseline_orgs(ref) end end +def graphql_response(batch, token) + variables = batch.each_with_index.to_h { |org, index| ["login#{index}", org] } + declarations = variables.keys.map { |name| "$#{name}: String!" }.join(', ') + fields = batch.each_index.map { |index| "org#{index}: organization(login: $login#{index}) { login }" } + Typhoeus.post( + 'https://api.github.com/graphql', + headers: { 'Authorization' => "Bearer #{token}", 'Content-Type' => 'application/json' }, + body: JSON.generate(query: "query(#{declarations}) { #{fields.join(' ')} }", variables: variables), + connecttimeout: 10, timeout: 60 + ) +end + +def parse_graphql_response(response) + return unless response.success? + + payload = JSON.parse(response.body) + return unless payload.is_a?(Hash) + + errors = payload.fetch('errors', []) + payload if errors.is_a?(Array) && errors.all? { |error| error.is_a?(Hash) } +rescue JSON::ParserError + nil +end + +def graphql_error(payload, index) + errors = payload.fetch('errors', []) + relevant = errors.select { |error| !error['path'].is_a?(Array) || error['path'].first == "org#{index}" } + return if relevant.empty? + + relevant.all? { |error| error['type'] == 'NOT_FOUND' && error['path'] == ["org#{index}"] } ? 'NOT_FOUND' : 'GraphQL error' +end + +def organization_result(payload, index) + return 'Invalid response' unless payload + + error = graphql_error(payload, index) + return error if error + + org = payload.dig('data', "org#{index}") if payload['data'].is_a?(Hash) + org.is_a?(Hash) && org['login'].is_a?(String) ? 'Organization' : 'Invalid response' +end + +def graphql_token + token = ENV.fetch('GITHUB_TOKEN', '') + abort 'Set GITHUB_TOKEN to check organizations with the GitHub GraphQL API.' if token.empty? + + token +end + +def check_organizations(candidates) + token = graphql_token unless candidates.empty? + responses = Hash.new(0) + results = {} + candidates.each_slice(50) do |batch| + response = graphql_response(batch, token) + responses[response.response_code] += 1 + payload = parse_graphql_response(response) + batch.each_with_index do |org, index| + results[org] = organization_result(payload, index) + end + end + puts "Responses (#{responses.values.sum} total):" + responses.sort.each { |code, count| puts "#{code.zero? ? 'No HTTP response' : "HTTP #{code}"}: #{count}" } + results.values.tally.sort.each { |result, count| puts "#{result}: #{count}" } + results +end + base_ref = ENV.fetch('ORG_BASE_REF', nil) existing_orgs = baseline_orgs(base_ref) unless base_ref.nil? || base_ref.empty? puts(existing_orgs ? 'Checking only added or renamed organizations.' : 'Checking all organizations.') +datasets = files.to_h { |file| [file, YAML.load_file(file)] } +candidates = datasets.values.flat_map { |data| data.values.flatten }.uniq +candidates.reject! { |org| existing_orgs.include?(org.downcase) } if existing_orgs +results = check_organizations(candidates) valid = true -response_counts = Hash.new(0) files.each do |file| - data = YAML.load_file file + data = datasets.fetch(file) data.each do |group, orgs| - candidates = existing_orgs ? orgs.reject { |org| existing_orgs.include?(org.downcase) } : orgs - responses = Parallel.map(candidates) do |org| - [org, Typhoeus.head("https://github.com/orgs/#{org}/people", accept_encoding: 'gzip')] - end - not_orgs = [] - responses.each do |org, response| - response_counts[response.response_code] += 1 - next if response.success? - - not_orgs << org if response.response_code == 404 - end + not_orgs = orgs.select { |org| results[org] == 'NOT_FOUND' } next if not_orgs.empty? - puts "\nIn #{File.basename(file)}, in the #{group} group, the following entries are not organizations or no longer exist (HTTP 404):\n\n" + puts "\nIn #{File.basename(file)}, in the #{group} group, the following entries are not organizations or no longer exist (GraphQL NOT_FOUND):\n\n" puts not_orgs valid = false data[group] = data[group] - not_orgs @@ -83,11 +128,7 @@ files.each do |file| File.write(file, output) end -puts "Responses (#{response_counts.values.sum} total):" -response_counts.sort.each do |code, count| - puts "#{code.zero? ? 'No HTTP response' : "HTTP #{code}"}: #{count}" -end -skipped = response_counts.sum { |code, count| code.between?(200, 299) || code == 404 ? 0 : count } +skipped = results.values.count { |result| !%w[Organization NOT_FOUND].include?(result) } puts "Skipped #{skipped} organization checks due to unavailable responses; entries retained." if skipped.positive? if valid diff --git a/test/ensure_orgs_test.rb b/test/ensure_orgs_test.rb index 601bf7a5..69cac81f 100644 --- a/test/ensure_orgs_test.rb +++ b/test/ensure_orgs_test.rb @@ -24,7 +24,34 @@ def write_baseline(dir, baseline) baseline.each_key { |name| File.delete("#{dir}/_data/#{name}.yml") } end - def run_check(codes, baseline: nil, current: nil, base_ref: nil) + def write_responses(dir) + File.write("#{dir}/responses.rb", <<~RUBY) + require 'typhoeus' + require 'json' + Typhoeus::Config.block_connection = true + Typhoeus.stub('https://api.github.com/graphql').and_return do |request| + raise 'Missing authentication' unless request.options[:headers]['Authorization'] == 'Bearer test-token' + body = JSON.parse(request.options.fetch(:body)) + codes = JSON.parse(ENV.fetch('ORG_RESPONSES')) + data = {} + errors = [] + body.fetch('variables').each do |variable, org| + result = codes.fetch(org) + name = variable.sub('login', 'org') + raise 'Missing query alias' unless body.fetch('query').include?("\#{name}: organization(login: $\#{variable})") + data[name] = result == 200 ? { 'login' => org } : nil + errors << { 'type' => result == 404 ? 'NOT_FOUND' : result, 'path' => [name] } unless result == 200 + end + options = JSON.parse(ENV.fetch('RESPONSE_OPTIONS')) + Typhoeus::Response.new( + code: options.fetch('code', 200), return_code: options.fetch('return_code', 'ok').to_sym, + body: options.fetch('body') { JSON.generate('data' => data, 'errors' => errors) } + ) + end + RUBY + end + + def run_check(codes, baseline: nil, current: nil, base_ref: nil, **options) Dir.mktmpdir do |dir| FileUtils.mkdir_p("#{dir}/script") FileUtils.mkdir_p("#{dir}/_data") @@ -36,18 +63,10 @@ def run_check(codes, baseline: nil, current: nil, base_ref: nil) end current ||= { 'Test' => codes.keys } File.write(data_path, "# Organizations\n\n#{current.to_yaml.sub(/\A---\n/, '')}") - File.write("#{dir}/responses.rb", <<~RUBY) - require 'typhoeus' - require 'json' - Typhoeus::Config.block_connection = true - JSON.parse(ENV.fetch('ORG_RESPONSES')).each do |org, code| - Typhoeus.stub("https://github.com/orgs/\#{org}/people").and_return( - Typhoeus::Response.new(code: code, return_code: code.zero? ? :operation_timedout : :ok) - ) - end - RUBY + write_responses(dir) output, status = Open3.capture2e( - { 'ORG_RESPONSES' => codes.to_json, 'GITHUB_ACTIONS' => 'true', 'ORG_BASE_REF' => base_ref }, + { 'ORG_RESPONSES' => codes.to_json, 'ORG_BASE_REF' => base_ref, 'GITHUB_TOKEN' => options.fetch(:token, 'test-token'), + 'RESPONSE_OPTIONS' => options.fetch(:response, {}).to_json }, Gem.ruby, '-r', "#{dir}/responses.rb", "#{dir}/script/ensure-orgs" ) [output, status, YAML.safe_load_file(data_path).values.flatten] @@ -59,29 +78,27 @@ class EnsureOrgsTest < Minitest::Test include EnsureOrgsFixtures def test_unavailable_responses_are_inconclusive_and_retained - codes = { 'org' => 200, 'forbidden' => 403, 'limited' => 429, 'server-error' => 500, - 'unavailable' => 503, 'timeout' => 0, 'redirect' => 302 } + codes = { 'org' => 200, 'forbidden' => 'FORBIDDEN', 'limited' => 'RATE_LIMITED' } output, status, entries = run_check(codes) assert status.success?, output assert_equal codes.keys, entries - assert_includes output, 'Skipped 6 organization checks' - assert_includes output, 'Responses (7 total):' - assert_includes output, 'HTTP 403: 1' - assert_includes output, 'HTTP 429: 1' - assert_includes output, 'No HTTP response: 1' + assert_includes output, 'Skipped 2 organization checks' + assert_includes output, 'Responses (1 total):' + assert_includes output, 'HTTP 200: 1' + assert_includes output, 'GraphQL error: 2' codes.keys.drop(1).each { |org| refute_includes output, "#{org}:" } refute_includes output, 'All orgs check out.' end def test_not_found_still_fails_without_removing_inconclusive_entries - output, status, entries = run_check({ 'org' => 200, 'user' => 404, 'limited' => 429 }) + output, status, entries = run_check({ 'org' => 200, 'user' => 404, 'limited' => 'RATE_LIMITED' }) assert_equal 1, status.exitstatus, output assert_equal %w[org limited], entries assert_includes output, 'not organizations or no longer exist' - assert_includes output, "(HTTP 404):\n\nuser\n" - assert_includes output, 'HTTP 404: 1' + assert_includes output, "(GraphQL NOT_FOUND):\n\nuser\n" + assert_includes output, 'NOT_FOUND: 1' assert_includes output, 'Skipped 1 organization checks' end @@ -103,8 +120,56 @@ def test_incremental_check_only_requests_added_and_renamed_orgs assert_equal 1, status.exitstatus, output assert_equal %w[Existing added], entries - assert_includes output, 'Responses (2 total):' - assert_includes output, "(HTTP 404):\n\nrenamed-new\n" + assert_includes output, 'Responses (1 total):' + assert_includes output, "(GraphQL NOT_FOUND):\n\nrenamed-new\n" + end + + class EnsureOrgsGraphqlTest < Minitest::Test + include EnsureOrgsFixtures + + def test_large_lists_are_split_into_batches + codes = 101.times.to_h { |index| ["org-#{index}", 200] } + output, status, entries = run_check(codes) + + assert status.success?, output + assert_equal codes.keys, entries + assert_includes output, 'Responses (3 total):' + assert_includes output, 'Organization: 101' + end + + def test_http_and_network_failures_retain_entries + [0, 403, 404, 429, 500, 503].each do |code| + response = { code: code, return_code: code.zero? ? 'operation_timedout' : 'ok' } + output, status, entries = run_check({ 'org' => 200 }, response: response) + + assert status.success?, output + assert_equal ['org'], entries + assert_includes output, 'Skipped 1 organization checks' + assert_includes output, code.zero? ? 'No HTTP response: 1' : "HTTP #{code}: 1" + end + end + + def test_malformed_and_global_errors_do_not_remove_entries + bodies = ['not json', 'null', '{}', '{"data":{"org0":null}}', + '{"errors":[{"type":"NOT_FOUND"}]}', + '{"data":{"org0":{"login":"org"}},"errors":[{"type":"RATE_LIMITED"}]}'] + bodies.each do |body| + output, status, entries = run_check({ 'org' => 200 }, response: { body: body }) + + assert status.success?, output + assert_equal ['org'], entries + assert_includes output, 'Skipped 1 organization checks' + refute_includes output, 'All orgs check out.' + end + end + + def test_missing_token_is_an_explicit_failure + output, status, entries = run_check({ 'org' => 200 }, token: nil) + + refute status.success?, output + assert_equal ['org'], entries + assert_includes output, 'Set GITHUB_TOKEN' + end end def test_moves_sorting_and_removals_do_not_request_orgs