0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-08 17:53:55 +08:00
discourse/plugins/discourse-github/app/lib/commits_populator.rb
Régis Hanol 36a8a51ef0
FEATURE: Route all GitHub API requests through one rate-limited client (#40637)
GitHub oneboxes and the discourse-github plugin talked to GitHub's REST
and
GraphQL API with no rate-limit awareness. On busy instances this
exhausted
GitHub's limits (60 requests/hour unauthenticated, 5000 authenticated),
and
because there was no backoff every render kept hitting GitHub and
re-failing
-- which GitHub's docs warn can get an integration banned. The recently
added PR-status onebox multiplied the number of calls and made it far
worse.

GitHub access was also fragmented: the core onebox engines used OpenURI,
the
discourse-github plugin used Octokit, and the discourse-ai bot tools
used
FinalDestination::HTTP -- three HTTP stacks, three tokens, and
inconsistent
(or entirely missing) error and rate-limit handling.

This introduces a single client, Discourse::GithubApi, that every GitHub
data-API request now flows through. It is built on Faraday with the
SSRF-safe
FinalDestination adapter and:

- authenticates per token (Bearer) and returns plain string-keyed Hashes
(get/post) or raw bodies (raw_get) -- one response shape, no
Octokit/Sawyer
- only ever sends the access token to api.github.com and
  raw.githubusercontent.com, rejecting any other absolute URL, so a
  user-derived path can never leak a token to an arbitrary host
- backs off on rate limits both reactively (403/429) and proactively
(when
X-RateLimit-Remaining hits 0), honouring Retry-After /
X-RateLimit-Reset,
via a shared Redis flag (GithubRateLimit) keyed per token so each
token's
  budget and the shared unauthenticated/IP budget back off independently
- short-circuits while backing off without ever sleeping, so onebox
rendering
  and post baking degrade to a plain link instead of blocking a request
- caches ETags and sends If-None-Match, so unchanged resources return
304s
  that do not count against the rate limit

Every caller was moved onto it:

- the 6 core GitHub onebox engines, via a slimmed
Onebox::Mixins::GithubApi
adapter that keeps their public methods and translates client errors
back
to the OpenURI::HTTPError vocabulary they already rescue (engines
unchanged)
- the github_blob raw.githubusercontent.com fetch
- the discourse-github plugin (badges, linkback, permalinks, token
validator),
which no longer uses the octokit and sawyer gems (they stay in the
Gemfile for
the discourse-code-review official plugin, which still depends on them)
- the discourse-ai bot's GitHub tools (search code, diff, file content,
  search files)

Also adds a GithubOneboxBackoff admin problem check that surfaces while
one of
the onebox token identities is backing off -- scoped to the tokens
resolved by
Onebox::GithubAccess (each configured github_onebox_access_tokens entry
plus the
unauthenticated client) so a backoff on the AI bot or linkback token is
not
misattributed to onebox. Its message points admins at the relevant
setting with
the {{setting:...}} link marker, which problem-check messages now expand
too.
Onebox token resolution is centralised in Onebox::GithubAccess, and the
onebox
cache TTL for transient GitHub failures is shortened so they recover
quickly.

GitHub OAuth login, theme git-clone, the inbound webhook, and the
Oneboxer
FinalDestination URL-resolution special-cases for github.com are
intentionally
out of scope -- they are different concerns, not the rate-limited data
API.
2026-06-15 10:59:10 +02:00

295 lines
9.4 KiB
Ruby
Vendored

# frozen_string_literal: true
module DiscourseGithubPlugin
class CommitsPopulator
MERGE_COMMIT_REGEX = /^Merge pull request/
HISTORY_COMPLETE = "history-complete"
class GraphQLError < StandardError
end
ROLES = { committer: 0, contributor: 1 }
class PaginatedCommits
def initialize(client, repo, cursor: nil, page_size: 100)
@client = client
@repo = repo
@cursor = cursor
@page_size = page_size
raise ArgumentError, "page_size arg must be <= 100" if page_size > 100
if cursor && !cursor.match?(/^\h{40}\s(\d+)$/)
raise ArgumentError,
"cursor must be a 40-characters hex string followed by a space and a number"
end
fetch_commits
end
def next
cursor = next_cursor
return unless cursor
PaginatedCommits.new(@client, @repo, cursor: cursor, page_size: @page_size)
end
def commits
history["nodes"]
end
def next_cursor
info = history["pageInfo"]
return unless info["hasNextPage"]
info["endCursor"]
end
private
def history
@data.dig("repository", "defaultBranchRef", "target", "history")
end
def fetch_commits
owner, name = @repo.name.split("/", 2)
history_args = "first: #{@page_size}"
history_args += ", after: #{@cursor.inspect}" if @cursor
query = <<~QUERY
query {
repository(name: #{name.inspect}, owner: #{owner.inspect}) {
defaultBranchRef {
target {
... on Commit {
history(#{history_args}) {
pageInfo {
endCursor
hasNextPage
}
nodes {
oid
message
committedDate
associatedPullRequests(first: 1) {
nodes {
author {
login
}
mergedBy {
login
}
}
}
author {
email
}
}
}
}
}
}
}
}
QUERY
response = @client.post("/graphql", { query: query })
raise GraphQLError, "Empty GraphQL response" if response.nil?
raise GraphQLError, response["errors"].inspect if response["errors"]
raise GraphQLError, response.inspect if !response["data"]
@data = response["data"]
end
end
def initialize(repo)
@repo = repo
@client = Discourse::GithubApi.for(token: SiteSetting.github_linkback_access_token)
end
def populate!
return unless SiteSetting.github_badges_enabled?
return if @client.backing_off?
return if @client.get("/repos/#{@repo.name}/branches").blank?
if @repo.commits.size == 0
build_history!
else
front_sha = Discourse.redis.get(front_commit_redis_key)
if front_sha.present? && removed?(front_sha)
# there has been a force push, next run will rebuild history
@repo.commits.delete_all
Discourse.redis.del(back_cursor_redis_key)
Discourse.redis.del(front_commit_redis_key)
return
end
fetch_new_commits!(front_sha)
front_sha = Discourse.redis.get(front_commit_redis_key)
@repo.reload
back_cursor = Discourse.redis.get(back_cursor_redis_key)
return if back_cursor == HISTORY_COMPLETE
if back_cursor.present?
build_history!(cursor: back_cursor)
elsif front_sha.present?
count = @repo.commits.count
build_history!(cursor: "#{front_sha} #{count - 1}")
else
# this is a bad state that we should never be in
# But in case it happens, easiest way to recover
# is to start from scratch.
@repo.commits.delete_all
Discourse.redis.del(back_cursor_redis_key)
Discourse.redis.del(front_commit_redis_key)
end
end
rescue Discourse::GithubApi::NotFound
disable_github_badges_and_inform_admin(
title: I18n.t("github_commits_populator.errors.repository_not_found_pm_title"),
raw:
I18n.t(
"github_commits_populator.errors.repository_not_found_pm",
repo_name: @repo.name,
base_path: Discourse.base_path,
),
)
Rails.logger.warn(
"Disabled github_badges_enabled site setting due to repository Not Found error ",
)
rescue Discourse::GithubApi::Unauthorized
disable_github_badges_and_inform_admin(
title: I18n.t("github_commits_populator.errors.invalid_octokit_credentials_pm_title"),
raw:
I18n.t(
"github_commits_populator.errors.invalid_octokit_credentials_pm",
base_path: Discourse.base_path,
),
)
Rails.logger.warn(
"Disabled github_badges_enabled site setting due to invalid GitHub authentication credentials via github_linkback_access_token.",
)
rescue Discourse::GithubApi::Error => err
Rails.logger.warn("#{err.class}: #{err.message}")
end
private
def is_contribution?(commit)
pr = commit.dig("associatedPullRequests", "nodes")&.first
pr && pr["author"] && pr["mergedBy"] &&
pr.dig("author", "login") != pr.dig("mergedBy", "login")
end
def fetch_new_commits!(stop_at)
paginator = PaginatedCommits.new(@client, @repo, page_size: 10)
batch = paginator.commits
done = false
commits = []
recent_commits =
stop_at.present? ? [] : @repo.commits.order("committed_at DESC").first(100).pluck(:sha)
while !done
batch.each do |c|
if c["oid"] == stop_at || recent_commits.include?(c["oid"])
done = true
break
end
commits << c
end
break if done
paginator = paginator.next
batch = paginator&.commits || []
break if batch.empty?
end
return if commits.size == 0
existing_shas = @repo.commits.pluck(:sha)
commits.reject! { |c| existing_shas.include?(c["oid"]) }
batch_to_db(commits)
set_front_commit(commits.first["oid"])
end
# detect if a force push happened and commit is lost
def removed?(sha)
commit = @client.get("/repos/#{@repo.name}/commits/#{sha}")
return false if commit.nil?
return true if commit["commit"].nil?
found =
@client.get(
"/repos/#{@repo.name}/commits",
until: commit.dig("commit", "committer", "date"),
page: 1,
per_page: 1,
).first
return false if found.nil?
commit["sha"] != found["sha"]
end
def build_history!(cursor: nil)
paginator = PaginatedCommits.new(@client, @repo, cursor: cursor, page_size: 100)
batch = paginator.commits
return if batch.empty?
set_front_commit(batch.first["oid"]) if cursor.blank?
while batch.size > 0
batch_to_db(batch)
next_cursor = paginator.next_cursor
set_back_cursor(next_cursor) if next_cursor
paginator = paginator.next
batch = paginator&.commits || []
end
set_back_cursor(HISTORY_COMPLETE)
end
def batch_to_db(batch)
fragments = []
batch.each do |c|
hash = commit_to_hash(c)
fragments << DB.sql_fragment(<<~SQL, hash)
(:repo_id, :sha, :email, :committed_at, :role_id, :merge_commit, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
SQL
end
DB.exec(<<~SQL)
INSERT INTO github_commits
(repo_id, sha, email, committed_at, role_id, merge_commit, created_at, updated_at) VALUES #{fragments.join(",")}
SQL
end
def commit_to_hash(commit)
{
sha: commit["oid"],
email: commit.dig("author", "email"),
repo_id: @repo.id,
committed_at: commit["committedDate"],
merge_commit: commit["message"].match?(MERGE_COMMIT_REGEX),
role_id: is_contribution?(commit) ? ROLES[:contributor] : ROLES[:committer],
}
end
def set_front_commit(sha)
Discourse.redis.set(front_commit_redis_key, sha)
end
def set_back_cursor(cursor)
Discourse.redis.set(back_cursor_redis_key, cursor)
end
def front_commit_redis_key
# this key should refer to the MOST RECENT commit we have in the db
"discourse-github-front-commit-#{@repo.name}"
end
def back_cursor_redis_key
# this key should refer to the cursor that lets us continue
# building history from the point we reached in the previous run
# that couldn't continue for whatever reasons
# e.g., if we got rate-limited by github
"discourse-github-back-cursor-#{@repo.name}"
end
def disable_github_badges_and_inform_admin(title:, raw:)
SiteSetting.github_badges_enabled = false
site_admin_usernames =
User.where(admin: true).human_users.order("last_seen_at DESC").limit(10).pluck(:username)
PostCreator.create!(
Discourse.system_user,
title: title,
raw: raw,
archetype: Archetype.private_message,
target_usernames: site_admin_usernames,
skip_validations: true,
)
end
end
end