feat(watchpr): poll GitHub PRs alongside Gitea
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline failed
ci/woodpecker/pr/test Pipeline was successful

This commit is contained in:
2026-11-22 01:51:26 +11:00
parent 10d93aaa90
commit 161a33c2ed
11 changed files with 983 additions and 32 deletions
+26 -6
View File
@@ -81,10 +81,15 @@ type GitHubApp struct {
APIURL string
HTTP *http.Client
mu sync.Mutex
token string
mu sync.Mutex
token string
expires time.Time
}
// tokenRefreshMargin is how long before expiry a cached installation token is
// re-minted, so a request never goes out with one about to lapse.
const tokenRefreshMargin = 5 * time.Minute
// ParseRSAPrivateKey decodes a PEM RSA key in PKCS#1 or PKCS#8 form. Errors
// never include key material.
func ParseRSAPrivateKey(pemData string) (*rsa.PrivateKey, error) {
@@ -155,19 +160,31 @@ func (a *GitHubApp) do(method, path, bearer string, out any) error {
}
// InstallationToken returns an installation access token, minted on first call
// and cached for the life of the process.
// and cached until it is within tokenRefreshMargin of expiry.
func (a *GitHubApp) InstallationToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
if a.token != "" {
if a.token != "" && time.Now().Before(a.expires.Add(-tokenRefreshMargin)) {
return a.token, nil
}
return a.mint()
}
// RefreshInstallationToken discards the cached token and mints a new one.
func (a *GitHubApp) RefreshInstallationToken() (string, error) {
a.mu.Lock()
defer a.mu.Unlock()
return a.mint()
}
func (a *GitHubApp) mint() (string, error) {
jwt, err := a.JWT(time.Now())
if err != nil {
return "", err
}
var out struct {
Token string `json:"token"`
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
path := "/app/installations/" + url.PathEscape(a.InstallationID) + "/access_tokens"
if err := a.do(http.MethodPost, path, jwt, &out); err != nil {
@@ -176,7 +193,10 @@ func (a *GitHubApp) InstallationToken() (string, error) {
if out.Token == "" {
return "", fmt.Errorf("github token mint for installation %s: no token in response", a.InstallationID)
}
a.token = out.Token
if out.ExpiresAt.IsZero() {
out.ExpiresAt = time.Now().Add(time.Hour)
}
a.token, a.expires = out.Token, out.ExpiresAt
return a.token, nil
}