-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub.go
More file actions
474 lines (407 loc) · 13 KB
/
github.go
File metadata and controls
474 lines (407 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package channels
import (
"bytes"
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"strconv"
"strings"
"sync"
"time"
"nuclaw/internal/config"
)
// GitHubAdapter handles GitHub issues and notifications.
type GitHubAdapter struct {
*BaseAdapter
cfg *config.Config
owner string
repo string
token string
client *http.Client
polling bool
stopCh chan struct{}
wg sync.WaitGroup
stopMu sync.Mutex
webhookSecret string
lastIssueUpdate time.Time
lastPRUpdate time.Time
logger *slog.Logger
}
// GHPullRequestRef represents a reference to a PR within an issue.
type GHPullRequestRef struct {
URL string `json:"url"`
HTMLURL string `json:"html_url"`
}
// GHIssue represents a GitHub issue.
type GHIssue struct {
ID int `json:"id"`
Number int `json:"number"`
Title string `json:"title"`
State string `json:"state"`
User GHUser `json:"user"`
Body string `json:"body"`
HTMLURL string `json:"html_url"`
PullRequest *GHPullRequestRef `json:"pull_request"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// GHUser represents a GitHub user.
type GHUser struct {
Login string `json:"login"`
ID int `json:"id"`
}
// GHPullRequest represents a GitHub pull request.
type GHPullRequest struct {
ID int `json:"id"`
Number int `json:"number"`
Title string `json:"title"`
State string `json:"state"`
User GHUser `json:"user"`
Body string `json:"body"`
HTMLURL string `json:"html_url"`
IsDraft bool `json:"draft"`
MergedAt *time.Time `json:"merged_at"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// GHComment represents a GitHub issue/PR comment.
type GHComment struct {
ID int `json:"id"`
Body string `json:"body"`
User GHUser `json:"user"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// GHIssueCommentEvent represents a webhook event payload.
type GHIssueCommentEvent struct {
Action string `json:"action"`
Issue GHIssue `json:"issue"`
Comment GHComment `json:"comment"`
Repo GHRepo `json:"repository"`
}
// GHRepo represents a GitHub repository.
type GHRepo struct {
Name string `json:"name"`
Owner GHUser `json:"owner"`
}
// NewGitHubAdapter creates a new GitHub adapter.
func NewGitHubAdapter(cfg *config.Config) (*GitHubAdapter, error) {
if cfg.GitHubOwner == "" || cfg.GitHubRepo == "" {
return nil, fmt.Errorf("GITHUB_OWNER and GITHUB_REPO are required")
}
return &GitHubAdapter{
BaseAdapter: NewBaseAdapter("github"),
cfg: cfg,
owner: cfg.GitHubOwner,
repo: cfg.GitHubRepo,
token: cfg.GitHubToken,
webhookSecret: cfg.GitHubWebhookSecret,
client: &http.Client{Timeout: 30 * time.Second},
stopCh: make(chan struct{}),
logger: slog.Default().With("channel", "github", "repo", cfg.GitHubOwner+"/"+cfg.GitHubRepo),
}, nil
}
// githubURL builds the API URL for the repository.
func (g *GitHubAdapter) githubURL(path string) string {
return "https://api.github.com" + path
}
// githubRequest creates an authenticated GitHub API request.
func (g *GitHubAdapter) githubRequest(ctx context.Context, method, url string, body []byte) (*http.Request, error) {
var bodyReader *bytes.Reader
if body != nil {
bodyReader = bytes.NewReader(body)
} else {
bodyReader = bytes.NewReader([]byte{})
}
req, err := http.NewRequestWithContext(ctx, method, url, bodyReader)
if err != nil {
return nil, fmt.Errorf("creating request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+g.token)
req.Header.Set("Accept", "application/vnd.github.v3+json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
return req, nil
}
// do executes a GitHub API request and returns the parsed response.
func (g *GitHubAdapter) do(ctx context.Context, method, path string, body []byte, result interface{}) error {
url := g.githubURL(path)
req, err := g.githubRequest(ctx, method, url, body)
if err != nil {
return err
}
resp, err := retryWithBackoff(ctx, defaultMaxRetries, defaultInitialBackoff, func() (*http.Response, error) {
return g.client.Do(req)
})
if err != nil {
return fmt.Errorf("request failed: %w", err)
}
defer func() { _ = resp.Body.Close() }()
// Check rate limit and log warning if running low
if rl := parseRateLimit(resp); rl.Remaining >= 0 && rl.Remaining <= 10 {
g.logger.Warn("GitHub rate limit low", "remaining", rl.Remaining, "limit", rl.Limit, "reset", rl.Reset)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("reading response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("GitHub API error (%d): %s", resp.StatusCode, string(respBody))
}
if result == nil {
return nil
}
if err := json.Unmarshal(respBody, result); err != nil {
return fmt.Errorf("unmarshaling response: %w", err)
}
return nil
}
// FetchMessages fetches new and updated issues and PRs from the repository.
func (g *GitHubAdapter) FetchMessages(ctx context.Context) ([]*Message, error) {
var issues []GHIssue
path := fmt.Sprintf("/repos/%s/%s/issues?state=all&per_page=30&sort=updated&direction=desc", g.owner, g.repo)
if err := g.do(ctx, "GET", path, nil, &issues); err != nil {
return nil, fmt.Errorf("fetching issues: %w", err)
}
prevIssueUpdate := g.lastIssueUpdate
var msgs []*Message
for _, issue := range issues {
// Deduplicate: compare against the timestamp from the *previous* poll,
// not the running max within this batch (which would skip all but the first).
if !issue.UpdatedAt.After(prevIssueUpdate) {
continue
}
// Track the newest timestamp seen in this batch for the next poll cycle.
if issue.UpdatedAt.After(g.lastIssueUpdate) {
g.lastIssueUpdate = issue.UpdatedAt
}
// Skip PRs - they'll be fetched separately
if issue.PullRequest != nil {
continue
}
msg := &Message{
ID: fmt.Sprintf("issue/%d", issue.ID),
ChannelType: "github",
PlatformID: fmt.Sprintf("%s/%s", g.owner, g.repo),
SenderID: strconv.Itoa(issue.User.ID),
SenderName: issue.User.Login,
Content: fmt.Sprintf("#%d: %s\n\n%s", issue.Number, issue.Title, issue.Body),
Timestamp: issue.UpdatedAt,
ThreadID: strconv.Itoa(issue.Number),
Raw: issue,
}
msgs = append(msgs, msg)
}
// Fetch PRs separately
var prs []GHPullRequest
prPath := fmt.Sprintf("/repos/%s/%s/pulls?state=all&per_page=30&sort=updated&direction=desc", g.owner, g.repo)
if err := g.do(ctx, "GET", prPath, nil, &prs); err != nil {
g.logger.Warn("fetching PRs failed", "error", err)
} else {
prevPRUpdate := g.lastPRUpdate
for _, pr := range prs {
if !pr.UpdatedAt.After(prevPRUpdate) {
continue
}
if pr.UpdatedAt.After(g.lastPRUpdate) {
g.lastPRUpdate = pr.UpdatedAt
}
state := pr.State
if pr.State == "closed" && pr.MergedAt != nil {
state = "merged"
}
msg := &Message{
ID: fmt.Sprintf("pr/%d", pr.ID),
ChannelType: "github",
PlatformID: fmt.Sprintf("%s/%s", g.owner, g.repo),
SenderID: strconv.Itoa(pr.User.ID),
SenderName: pr.User.Login,
Content: fmt.Sprintf("PR #%d: %s (%s)\n\n%s", pr.Number, pr.Title, state, pr.Body),
Timestamp: pr.UpdatedAt,
ThreadID: strconv.Itoa(pr.Number),
Raw: pr,
}
msgs = append(msgs, msg)
}
}
return msgs, nil
}
// SendMessage sends a message via GitHub.
// platformID can be:
// - Issue number: "123" -> adds comment to issue #123
// - PR number: "pr/123" -> adds comment to PR #123
// - "new" -> creates a new issue
func (g *GitHubAdapter) SendMessage(ctx context.Context, platformID string, msg *OutgoingMessage) error {
if platformID == "" {
return fmt.Errorf("platformID (issue/PR number) is required")
}
// Check if creating new issue
if platformID == "new" {
return g.createIssue(ctx, msg)
}
// Parse the target (issue or PR number)
targetNum := platformID
isPR := false
if strings.HasPrefix(strings.ToLower(platformID), "pr/") {
targetNum = strings.TrimPrefix(platformID, "pr/")
isPR = true
}
num, err := strconv.Atoi(targetNum)
if err != nil {
return fmt.Errorf("invalid issue/PR number: %w", err)
}
return g.addComment(ctx, num, isPR, msg.Content)
}
// createIssue creates a new issue.
func (g *GitHubAdapter) createIssue(ctx context.Context, msg *OutgoingMessage) error {
type IssueRequest struct {
Title string `json:"title"`
Body string `json:"body"`
}
parts := strings.SplitN(msg.Content, "\n", 2)
title := strings.TrimRight(parts[0], "\r")
body := ""
if len(parts) > 1 {
body = parts[1]
}
// Extract title from ThreadID if provided
if msg.ThreadID != "" {
threadNum, err := strconv.Atoi(msg.ThreadID)
if err == nil {
title = fmt.Sprintf("Issue #%d", threadNum)
}
}
reqBody, err := json.Marshal(IssueRequest{
Title: title,
Body: body,
})
if err != nil {
return fmt.Errorf("marshaling request: %w", err)
}
path := fmt.Sprintf("/repos/%s/%s/issues", g.owner, g.repo)
if err := g.do(ctx, "POST", path, reqBody, nil); err != nil {
return fmt.Errorf("creating issue: %w", err)
}
return nil
}
// addComment adds a comment to an issue or PR.
// Both issue and PR comments use the /issues/{number}/comments endpoint
// (GitHub treats PRs as issues). The isPR parameter is retained for callers
// that need to distinguish the target type in logs or future behavior.
func (g *GitHubAdapter) addComment(ctx context.Context, num int, isPR bool, content string) error {
type CommentRequest struct {
Body string `json:"body"`
}
reqBody, err := json.Marshal(CommentRequest{Body: content})
if err != nil {
return fmt.Errorf("marshaling request: %w", err)
}
// Both issues and PRs use the same comments endpoint.
// The /pulls/{num}/comments endpoint is for review comments on specific diffs.
path := fmt.Sprintf("/repos/%s/%s/issues/%d/comments", g.owner, g.repo, num)
if err := g.do(ctx, "POST", path, reqBody, nil); err != nil {
return fmt.Errorf("adding comment: %w", err)
}
return nil
}
// StartPolling starts the polling loop.
func (g *GitHubAdapter) StartPolling(ctx context.Context, handler func(*Message) error, interval time.Duration) error {
g.stopMu.Lock()
defer g.stopMu.Unlock()
if g.polling {
return fmt.Errorf("already polling")
}
g.polling = true
g.stopCh = make(chan struct{})
g.wg.Add(1)
go func() {
defer g.wg.Done()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-g.stopCh:
return
case <-ticker.C:
msgs, err := g.FetchMessages(ctx)
if err != nil {
g.logger.Error("fetch error", "error", err)
continue
}
for _, msg := range msgs {
if err := handler(msg); err != nil {
g.logger.Error("handler error", "error", err)
}
}
}
}
}()
return nil
}
// StopPolling stops the polling loop.
func (g *GitHubAdapter) StopPolling() error {
g.stopMu.Lock()
defer g.stopMu.Unlock()
if !g.polling {
return nil
}
g.polling = false
close(g.stopCh)
g.wg.Wait()
// stopCh is left closed — StartPolling creates a fresh one.
return nil
}
// HandleWebhook processes a GitHub webhook event.
// The payload should be the raw request body, and signature should be the X-Hub-Signature-256 header.
func (g *GitHubAdapter) HandleWebhook(payload []byte, signature string) (*Message, error) {
if g.webhookSecret != "" {
if err := g.verifySignature(payload, signature); err != nil {
return nil, fmt.Errorf("webhook signature verification failed: %w", err)
}
}
var event GHIssueCommentEvent
if err := json.Unmarshal(payload, &event); err != nil {
return nil, fmt.Errorf("parsing webhook: %w", err)
}
msg := &Message{
ID: fmt.Sprintf("comment/%d", event.Comment.ID),
ChannelType: "github",
PlatformID: fmt.Sprintf("%s/%s", g.owner, g.repo),
SenderID: strconv.Itoa(event.Comment.User.ID),
SenderName: event.Comment.User.Login,
Content: event.Comment.Body,
Timestamp: event.Comment.CreatedAt,
ThreadID: strconv.Itoa(event.Issue.Number),
Raw: event,
}
return msg, nil
}
// verifySignature validates the X-Hub-Signature-256 HMAC hex digest.
func (g *GitHubAdapter) verifySignature(payload []byte, signatureHeader string) error {
const prefix = "sha256="
if !strings.HasPrefix(signatureHeader, prefix) {
return fmt.Errorf("signature missing sha256= prefix")
}
sigHex := strings.TrimPrefix(signatureHeader, prefix)
sig, err := hex.DecodeString(sigHex)
if err != nil {
return fmt.Errorf("decoding signature hex: %w", err)
}
mac := hmac.New(sha256.New, []byte(g.webhookSecret))
mac.Write(payload)
expected := mac.Sum(nil)
if !hmac.Equal(sig, expected) {
return fmt.Errorf("signature mismatch")
}
return nil
}
// Ensure GitHubAdapter implements Adapter
var _ Adapter = (*GitHubAdapter)(nil)