-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbot.go
More file actions
1855 lines (1671 loc) · 64.9 KB
/
bot.go
File metadata and controls
1855 lines (1671 loc) · 64.9 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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package bot implements the coordination logic between GitHub, Slack, and notifications.
package bot
import (
"context"
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"sync"
"time"
"github.com/codeGROOVE-dev/slacker/pkg/config"
"github.com/codeGROOVE-dev/slacker/pkg/notify"
"github.com/codeGROOVE-dev/slacker/pkg/state"
"github.com/codeGROOVE-dev/slacker/pkg/usermapping"
"github.com/codeGROOVE-dev/turnclient/pkg/turn"
)
// Common logging constants.
const (
logFieldPR = "pr"
logFieldRepo = "repo"
logFieldOwner = "owner"
logFieldChannel = "channel"
prFormatString = "%s/%s#%d"
historyPageSize = 1000
)
// prContext groups PR identification parameters to reduce function argument counts.
type prContext struct {
CheckRes *turn.CheckResponse
Event any // The webhook event struct
Owner string
Repo string
State string
Number int
}
// ThreadCache manages PR thread IDs for a workspace.
//
//nolint:govet // Field order optimized for logical grouping over memory alignment
type ThreadCache struct {
mu sync.RWMutex
creationLock sync.Mutex // Prevents concurrent creation of the same PR thread
prThreads map[string]ThreadInfo // "owner/repo#123" -> thread info
creating map[string]bool // Track PRs currently being created
}
// ThreadInfo is an alias to state.ThreadInfo to avoid duplication.
type ThreadInfo = state.ThreadInfo
// CommitPREntry caches recent commit→PR mappings for fast lookup.
type CommitPREntry struct {
PRNumber int
HeadSHA string
UpdatedAt time.Time
}
// CommitPRCache provides in-memory caching of commit SHA → PR mappings.
// This allows quick lookup when check events arrive with just a commit SHA,
// avoiding expensive GitHub API calls for recently-seen PRs.
type CommitPRCache struct {
mu sync.RWMutex
entries map[string][]CommitPREntry // "owner/repo" -> recent PRs with commits
}
// Get retrieves thread info for a PR.
func (tc *ThreadCache) Get(prKey string) (ThreadInfo, bool) {
tc.mu.RLock()
defer tc.mu.RUnlock()
info, exists := tc.prThreads[prKey]
return info, exists
}
// Set stores thread info for a PR.
func (tc *ThreadCache) Set(prKey string, info ThreadInfo) {
tc.mu.Lock()
defer tc.mu.Unlock()
info.UpdatedAt = time.Now()
tc.prThreads[prKey] = info
}
// Cleanup removes entries older than the specified age.
// This prevents unbounded memory growth for closed/merged PRs.
func (tc *ThreadCache) Cleanup(maxAge time.Duration) {
tc.mu.Lock()
defer tc.mu.Unlock()
cutoff := time.Now().Add(-maxAge)
for key, info := range tc.prThreads {
if info.UpdatedAt.Before(cutoff) {
delete(tc.prThreads, key)
}
}
}
// RecordPR records a PR's head commit SHA for commit→PR lookups.
// Entries are kept for 10 minutes to handle check events that arrive shortly after PR events.
func (cpc *CommitPRCache) RecordPR(owner, repo string, prNumber int, headSHA string) {
if headSHA == "" {
return // Skip empty commits
}
cpc.mu.Lock()
defer cpc.mu.Unlock()
repoKey := owner + "/" + repo
now := time.Now()
// Initialize map if needed
if cpc.entries == nil {
cpc.entries = make(map[string][]CommitPREntry)
}
// Add new entry
entry := CommitPREntry{
PRNumber: prNumber,
HeadSHA: headSHA,
UpdatedAt: now,
}
// Get existing entries for this repo
entries := cpc.entries[repoKey]
// Check if this exact PR+commit combination already exists - update timestamp if so
found := false
for i := range entries {
if entries[i].PRNumber == prNumber && entries[i].HeadSHA == headSHA {
entries[i].UpdatedAt = now // Refresh timestamp
found = true
break
}
}
if !found {
entries = append(entries, entry)
}
// Update the map with the modified entries before filtering
cpc.entries[repoKey] = entries
// Keep only entries from last 10 minutes (check events usually arrive within seconds)
cutoff := now.Add(-10 * time.Minute)
filtered := make([]CommitPREntry, 0, len(entries))
for i := range entries {
if entries[i].UpdatedAt.After(cutoff) {
filtered = append(filtered, entries[i])
}
}
cpc.entries[repoKey] = filtered
}
// FindPRsForCommit finds PRs in a repo that match the given commit SHA.
// Returns PR numbers if found in recent cache (last 10 minutes), nil otherwise.
func (cpc *CommitPRCache) FindPRsForCommit(owner, repo, commitSHA string) []int {
if commitSHA == "" {
return nil
}
cpc.mu.RLock()
defer cpc.mu.RUnlock()
repoKey := owner + "/" + repo
entries, exists := cpc.entries[repoKey]
if !exists {
return nil
}
// Check which PRs have this commit
var prNumbers []int
for i := range entries {
if entries[i].HeadSHA == commitSHA {
prNumbers = append(prNumbers, entries[i].PRNumber)
}
}
return prNumbers
}
// MostRecentPR returns the most recently updated PR number for a repo from the cache.
// Returns 0 if no recent PRs are cached for this repo.
func (cpc *CommitPRCache) MostRecentPR(owner, repo string) int {
cpc.mu.RLock()
defer cpc.mu.RUnlock()
repoKey := owner + "/" + repo
entries, exists := cpc.entries[repoKey]
if !exists || len(entries) == 0 {
return 0
}
// Find the entry with the most recent UpdatedAt timestamp
mostRecent := entries[0]
for i := 1; i < len(entries); i++ {
if entries[i].UpdatedAt.After(mostRecent.UpdatedAt) {
mostRecent = entries[i]
}
}
return mostRecent.PRNumber
}
// Coordinator coordinates between GitHub, Slack, and notifications for a single org.
//
//nolint:govet // Field order optimized for logical grouping over memory alignment
type Coordinator struct {
processingEvents sync.WaitGroup // Tracks in-flight event processing for graceful shutdown
stateStore StateStore // Persistent state across restarts
sprinklerURL string
workspaceName string // Track workspace name for better logging
slack SlackClient
github GitHubClient
configManager *config.Manager
notifier *notify.Manager
userMapper *usermapping.Service
threadCache *ThreadCache // In-memory cache for fast lookups
commitPRCache *CommitPRCache // Maps commit SHAs to PR numbers for check events
eventSemaphore chan struct{} // Limits concurrent event processing (prevents overwhelming APIs)
}
// StateStore interface for persistent state - allows dependency injection for testing.
type StateStore interface {
Thread(owner, repo string, number int, channelID string) (ThreadInfo, bool)
SaveThread(owner, repo string, number int, channelID string, info ThreadInfo) error
LastDM(userID, prURL string) (time.Time, bool)
RecordDM(userID, prURL string, sentAt time.Time) error
ListDMUsers(prURL string) []string
WasProcessed(eventKey string) bool
MarkProcessed(eventKey string, ttl time.Duration) error
LastNotification(prURL string) time.Time
RecordNotification(prURL string, notifiedAt time.Time) error
Close() error
}
// New creates a new bot coordinator for a single GitHub organization.
func New(
ctx context.Context,
slackClient SlackClient,
githubClient GitHubClient,
configManager *config.Manager,
notifier *notify.Manager,
sprinklerURL string,
stateStore StateStore,
) *Coordinator {
c := &Coordinator{
slack: slackClient,
github: githubClient,
configManager: configManager,
notifier: notifier,
userMapper: usermapping.New(slackClient.API(), githubClient.InstallationToken(ctx)),
sprinklerURL: sprinklerURL,
stateStore: stateStore,
threadCache: &ThreadCache{
prThreads: make(map[string]ThreadInfo),
creating: make(map[string]bool),
},
commitPRCache: &CommitPRCache{
entries: make(map[string][]CommitPREntry),
},
eventSemaphore: make(chan struct{}, 10), // Allow 10 concurrent events per org
}
// Set GitHub client in config manager for this org.
org := githubClient.Organization()
if ghClient := githubClient.Client(); ghClient != nil {
configManager.SetGitHubClient(org, ghClient)
}
// Get workspace info and set in config manager for validation.
if teamInfo, err := slackClient.WorkspaceInfo(ctx); err == nil {
// Use the team domain as workspace identifier
workspaceName := teamInfo.Domain + ".slack.com"
c.workspaceName = workspaceName
configManager.SetWorkspaceName(workspaceName)
slog.Info("initialized bot coordinator",
"workspace", workspaceName,
"workspace_id", teamInfo.ID,
"workspace_domain", teamInfo.Domain,
"ready_for_events", true)
} else {
slog.Warn("failed to get workspace info, config validation disabled", "error", err)
}
return c
}
// saveThread persists thread info to both cache and persistent storage.
// This ensures threads survive restarts and are available for closed PR updates.
func (c *Coordinator) saveThread(owner, repo string, number int, channelID string, info ThreadInfo) {
// Save to in-memory cache for fast lookups
key := fmt.Sprintf("%s/%s#%d:%s", owner, repo, number, channelID)
c.threadCache.Set(key, info)
// Persist to state store for cross-instance sharing and restart recovery
if err := c.stateStore.SaveThread(owner, repo, number, channelID, info); err != nil {
slog.Warn("failed to persist thread to state store",
"pr", fmt.Sprintf("%s/%s#%d", owner, repo, number),
"channel_id", channelID,
"error", err,
"impact", "thread updates may fail after restart")
} else {
slog.Debug("persisted thread to state store",
"pr", fmt.Sprintf("%s/%s#%d", owner, repo, number),
"channel_id", channelID,
"thread_ts", info.ThreadTS)
}
}
// findOrCreatePRThread finds an existing thread or creates a new one for a PR.
// Returns (threadTS, wasNewlyCreated, currentMessageText, error).
//
//nolint:revive // Four return values needed to track thread state and creation status
func (c *Coordinator) findOrCreatePRThread(ctx context.Context, channelID, owner, repo string, prNumber int, prState string, pullRequest struct {
CreatedAt time.Time `json:"created_at"`
User struct {
Login string `json:"login"`
} `json:"user"`
HTMLURL string `json:"html_url"`
Title string `json:"title"`
Number int `json:"number"`
}, checkResult *turn.CheckResponse,
) (threadTS string, wasNewlyCreated bool, currentMessageText string, err error) {
// Use cache key that includes channel ID to support multiple channels per PR
cacheKey := fmt.Sprintf("%s/%s#%d:%s", owner, repo, prNumber, channelID)
slog.Debug("finding or creating PR thread",
"pr", cacheKey,
logFieldChannel, channelID,
"pr_state", prState)
// Check cache first (quick read lock)
if threadInfo, exists := c.threadCache.Get(cacheKey); exists {
slog.Debug("found PR thread in cache",
"pr", cacheKey,
"thread_ts", threadInfo.ThreadTS,
logFieldChannel, channelID,
"cached_state", threadInfo.LastState,
"has_cached_message_text", threadInfo.MessageText != "")
return threadInfo.ThreadTS, false, threadInfo.MessageText, nil
}
// Not in cache - search Slack for existing thread before trying to create
prURL := fmt.Sprintf("https://github.com/%s/%s/pull/%d", owner, repo, prNumber)
searchFrom := pullRequest.CreatedAt
if searchFrom.IsZero() || time.Since(searchFrom) > 30*24*time.Hour {
searchFrom = time.Now().AddDate(0, 0, -30) // 30 days fallback
slog.Debug("using 30-day fallback for thread search",
"pr", cacheKey,
"pr_created_at_available", !pullRequest.CreatedAt.IsZero(),
"pr_age_days", int(time.Since(pullRequest.CreatedAt).Hours()/24))
} else {
slog.Debug("using PR creation date for thread search",
"pr", cacheKey,
"pr_created_at", searchFrom.Format(time.RFC3339),
"search_window_days", int(time.Since(searchFrom).Hours()/24))
}
initialSearchTS, initialSearchText := c.searchForPRThread(ctx, channelID, prURL, searchFrom)
if initialSearchTS != "" {
slog.Info("found existing PR thread via initial search",
"pr", cacheKey,
"thread_ts", initialSearchTS,
logFieldChannel, channelID,
"current_message_preview", initialSearchText[:min(100, len(initialSearchText))])
// Save the found thread (cache + persist)
c.saveThread(owner, repo, prNumber, channelID, ThreadInfo{
ThreadTS: initialSearchTS,
ChannelID: channelID,
LastState: prState,
MessageText: initialSearchText,
})
return initialSearchTS, false, initialSearchText, nil
}
// Prevent concurrent creation of the same PR thread in same channel
// Lock on cacheKey (with channel) to allow parallel creation in different channels
c.threadCache.creationLock.Lock()
// Check if another goroutine is already creating this thread in this channel
if c.threadCache.creating[cacheKey] {
c.threadCache.creationLock.Unlock()
// Wait for the other goroutine to finish (up to 30 seconds)
slog.Info("another goroutine is creating this PR thread, waiting for completion",
"pr", cacheKey)
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
time.Sleep(500 * time.Millisecond)
if threadInfo, exists := c.threadCache.Get(cacheKey); exists {
slog.Info("found PR thread after waiting for concurrent creation",
"pr", cacheKey,
"thread_ts", threadInfo.ThreadTS,
"waited", time.Since(time.Now().Add(-30*time.Second)))
return threadInfo.ThreadTS, false, "", nil
}
// Check if the other goroutine finished (even if it failed)
c.threadCache.creationLock.Lock()
stillCreating := c.threadCache.creating[cacheKey]
c.threadCache.creationLock.Unlock()
if !stillCreating {
// Other goroutine finished but didn't cache (likely failed)
// Proceed to try creating ourselves
break
}
}
slog.Warn("timed out waiting for concurrent thread creation, will try creating ourselves",
"pr", cacheKey)
c.threadCache.creationLock.Lock()
}
// Double-check cache while holding lock (another goroutine might have just finished)
if threadInfo, exists := c.threadCache.Get(cacheKey); exists {
c.threadCache.creationLock.Unlock()
slog.Debug("found PR thread in cache during lock acquisition",
"pr", cacheKey,
"thread_ts", threadInfo.ThreadTS)
return threadInfo.ThreadTS, false, "", nil
}
// Mark as creating
c.threadCache.creating[cacheKey] = true
c.threadCache.creationLock.Unlock()
// Ensure we clean up the creating flag
defer func() {
c.threadCache.creationLock.Lock()
delete(c.threadCache.creating, cacheKey)
c.threadCache.creationLock.Unlock()
}()
// CRITICAL: Perform one final cross-instance check RIGHT before the expensive operations
// This handles the case where another instance (during rolling deployment) just created
// a thread while we were acquiring the lock. The creating flag only prevents races within
// this instance - we need to check Slack itself to catch threads from other instances.
// Add a small delay to let any concurrent creates from other instances complete their Slack API call.
time.Sleep(100 * time.Millisecond)
crossInstanceCheckTS, crossInstanceText := c.searchForPRThread(ctx, channelID, prURL, pullRequest.CreatedAt)
if crossInstanceCheckTS != "" {
slog.Info("found thread created by another instance (cross-instance race avoided)",
"pr", cacheKey,
"thread_ts", crossInstanceCheckTS,
logFieldChannel, channelID,
"current_message_preview", crossInstanceText[:min(100, len(crossInstanceText))],
"note", "this prevented duplicate thread creation during rolling deployment")
// Save it and return (cache + persist)
c.saveThread(owner, repo, prNumber, channelID, ThreadInfo{
ThreadTS: crossInstanceCheckTS,
ChannelID: channelID,
LastState: prState,
MessageText: crossInstanceText,
})
return crossInstanceCheckTS, false, crossInstanceText, nil
}
// Create new thread
slog.Info("creating new PR thread",
"pr", cacheKey,
logFieldChannel, channelID,
"pr_state", prState,
"pr_created_at", pullRequest.CreatedAt.Format(time.RFC3339),
"search_window_used", searchFrom.Format(time.RFC3339))
newThreadTS, newMessageText, err := c.createPRThread(ctx, channelID, owner, repo, prNumber, prState, pullRequest, checkResult)
if err != nil {
return "", false, "", fmt.Errorf("failed to create PR thread: %w", err)
}
// Save the new thread (cache + persist)
c.saveThread(owner, repo, prNumber, channelID, ThreadInfo{
ThreadTS: newThreadTS,
ChannelID: channelID,
LastState: prState,
MessageText: newMessageText,
})
slog.Info("created and cached new PR thread",
"pr", cacheKey,
"thread_ts", newThreadTS,
logFieldChannel, channelID,
"initial_state", prState,
"message_preview", newMessageText[:min(100, len(newMessageText))],
"creation_successful", true,
"note", "if you see duplicate threads, check if another instance created one during the same time window")
return newThreadTS, true, newMessageText, nil
}
// searchForPRThread searches for an existing PR thread in a channel using channel history.
// This approach uses channels:history permission instead of search:read which isn't available to bots.
// Note: This is more expensive than search API but works reliably with basic bot permissions.
// Results are cached by the calling code to minimize API calls.
// Returns (threadTS, currentMessageText) - both empty if not found.
func (c *Coordinator) searchForPRThread(ctx context.Context, channelID, prURL string, prCreatedAt time.Time) (threadTS string, messageText string) {
slog.Info("searching for existing PR thread using channel history",
logFieldChannel, channelID,
"pr_url", prURL)
// Get bot info to identify our messages
botInfo, err := c.slack.BotInfo(ctx)
if err != nil {
slog.Warn("failed to get bot info, cannot search for existing threads",
logFieldChannel, channelID,
"error", err)
// Return empty strings to indicate no thread found
return "", ""
}
// Search from PR creation date (more efficient than arbitrary 10 days)
// Slack timestamps are in seconds since epoch
ts := prCreatedAt.Unix()
oldestTimestamp := strconv.FormatInt(ts, 10)
slog.Debug("searching channel history for bot messages",
logFieldChannel, channelID,
"bot_user_id", botInfo.UserID,
"oldest_timestamp", oldestTimestamp,
"pr_created_at", prCreatedAt.Format(time.RFC3339),
"looking_for_url", prURL)
// Get channel history - limit to 1000 messages for performance
history, err := c.slack.ChannelHistory(ctx, channelID, oldestTimestamp, "", historyPageSize)
if err != nil {
slog.Warn("failed to get channel history",
logFieldChannel, channelID,
"error", err)
// Return empty strings to indicate no thread found
// This allows graceful fallback to creating new threads
return "", ""
}
slog.Info("retrieved messages from channel history for PR thread search",
logFieldChannel, channelID,
"messages_count", len(history.Messages),
"search_from", prCreatedAt.Format(time.RFC3339),
"oldest_timestamp", oldestTimestamp,
"bot_user_id", botInfo.UserID,
"searching_for_url", prURL)
// Look through messages for bot-posted threads containing the PR URL
// Note: We search for the base URL because posted messages may include state query params
// like "?st=awaiting_review" which change as the PR progresses
checked := 0
for i := range history.Messages {
msg := &history.Messages[i]
// Only check messages from our bot
if msg.User != botInfo.UserID {
continue
}
checked++
slog.Debug("checking bot message for PR URL",
logFieldChannel, channelID,
"message_ts", msg.Timestamp,
"message_text", msg.Text,
"looking_for", prURL,
"contains_url", strings.Contains(msg.Text, prURL))
// Check if this message contains the PR URL (base URL, before any query parameters)
// The message may contain URLs like "https://github.com/org/repo/pull/32?st=awaiting_review"
// but we search for the base "https://github.com/org/repo/pull/32"
if strings.Contains(msg.Text, prURL) {
// Parse timestamp to calculate message age
var messageAgeHours int
if ts, err := strconv.ParseFloat(msg.Timestamp, 64); err == nil {
messageAgeHours = int(time.Since(time.Unix(int64(ts), 0)).Hours())
}
slog.Info("found existing PR thread via channel history",
logFieldChannel, channelID,
"thread_ts", msg.Timestamp,
"pr_url", prURL,
"message_age_hours", messageAgeHours,
"message_preview", msg.Text[:min(100, len(msg.Text))])
return msg.Timestamp, msg.Text
}
}
slog.Info("no matching PR thread found in channel history",
logFieldChannel, channelID,
"pr_url", prURL,
"total_messages_retrieved", len(history.Messages),
"bot_messages_checked", checked,
"bot_user_id", botInfo.UserID)
return "", ""
}
// SprinklerMessage represents a message from sprinkler.
type SprinklerMessage struct {
Timestamp time.Time `json:"timestamp,omitempty"` // Event timestamp from sprinkler
Type string `json:"type,omitempty"` // Message type (e.g., "ping", "event")
Event string `json:"event,omitempty"` // GitHub event type
Repo string `json:"repo,omitempty"` // Repository name
URL string `json:"url,omitempty"` // GitHub URL for reference
PRNumber int `json:"pr_number,omitempty"` // PR number extracted from URL
}
// processEvent processes a GitHub webhook event.
func (c *Coordinator) processEvent(ctx context.Context, msg SprinklerMessage) error {
// Skip empty messages (likely subscription confirmations or keepalives)
if msg.Event == "" && msg.Repo == "" {
slog.Debug("received empty message from sprinkler, likely acknowledgment")
return nil
}
// Skip messages without repo information
if msg.Repo == "" {
slog.Debug("received message without repo", "event", msg.Event)
return nil
}
slog.Info("processing event", "event", msg.Event, "repo", msg.Repo)
// Parse repo owner and name.
parts := strings.Split(msg.Repo, "/")
if len(parts) != 2 {
slog.Warn("invalid repo format", "repo", msg.Repo)
return fmt.Errorf("invalid repo format: %s", msg.Repo)
}
owner := parts[0]
repo := parts[1]
if owner == "" || repo == "" {
slog.Warn("empty owner or repo name", "owner", owner, "repo", repo)
return errors.New("empty owner or repo name")
}
// Load config for this org if not already loaded.
if _, exists := c.configManager.Config(owner); !exists {
if err := c.configManager.LoadConfig(ctx, owner); err != nil {
slog.Warn("failed to load config for org", "org", owner, "error", err)
}
}
// Handle different event types.
switch msg.Event {
case "pull_request":
// Special handling for .codeGROOVE repo pull requests
if repo == ".codeGROOVE" {
slog.Info("received pull request event for .codeGROOVE repo",
"org", owner,
"pr", msg.PRNumber,
"will_invalidate_cache_on_merge", true)
// Note: Cache will be invalidated on push event when PR is merged
}
c.handlePullRequestFromSprinkler(ctx, owner, repo, msg.PRNumber, msg.URL, msg.Timestamp)
case "pull_request_review":
c.handlePullRequestReviewFromSprinkler(ctx, owner, repo, msg.PRNumber, msg.URL, msg.Timestamp)
case "check_run", "check_suite":
// Check events update PR test status - handle like pull_request events
if msg.PRNumber > 0 {
slog.Info("received check event for PR, refreshing state",
"owner", owner,
"repo", repo,
"pr", msg.PRNumber,
"event", msg.Event)
c.handlePullRequestFromSprinkler(ctx, owner, repo, msg.PRNumber, msg.URL, msg.Timestamp)
} else {
slog.Debug("received check event without PR number, skipping",
"owner", owner,
"repo", repo,
"event", msg.Event,
"url", msg.URL)
}
case "push":
// Check if this is a push to .codeGROOVE repo.
if repo == ".codeGROOVE" {
slog.Info("reloading config due to push to .codeGROOVE repo",
"org", owner,
"invalidating_cache", true)
if err := c.configManager.ReloadConfig(ctx, owner); err != nil {
slog.Warn("failed to reload config", "error", err)
}
}
default:
slog.Debug("unhandled event type", "event", msg.Event)
}
return nil
}
// handlePullRequestEventWithData handles pull request events with pre-fetched data to avoid redundant API calls.
func (c *Coordinator) handlePullRequestEventWithData(ctx context.Context, owner, repo string, event struct {
Action string `json:"action"`
PullRequest struct {
HTMLURL string `json:"html_url"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
User struct {
Login string `json:"login"`
} `json:"user"`
Number int `json:"number"`
} `json:"pull_request"`
Number int `json:"number"`
}, checkResult *turn.CheckResponse, _ any,
) {
prNumber := event.Number
slog.Info("PR event with pre-fetched data",
logFieldOwner, owner,
logFieldRepo, repo,
"number", prNumber,
"action", event.Action)
// Load workspace and organization configuration
if err := c.configManager.LoadConfig(ctx, owner); err != nil {
slog.Error("failed to load config for org",
"org", owner,
"error", err)
return
}
// Get workspace name from config for proper multi-workspace support
workspaceID := c.configManager.WorkspaceName(owner)
// Get channels for this PR
channels := c.configManager.ChannelsForRepo(owner, repo)
slog.Debug("evaluating PR for channel notifications",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"action", event.Action,
"title", event.PullRequest.Title,
"author", event.PullRequest.User.Login,
"configured_channels", len(channels),
"channels", channels)
if len(channels) == 0 {
slog.Info("no channels configured for PR - skipping channel notifications",
logFieldOwner, owner,
logFieldRepo, repo,
"pr_number", prNumber)
return
}
// Extract state from turnclient response instead of making additional API calls
prState := c.extractStateFromTurnclient(checkResult)
blockedOn := c.extractBlockedUsersFromTurnclient(checkResult)
slog.Debug("retrieved PR state for notification processing",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"state", prState,
"blocked_on_users", len(blockedOn),
"blocked_on", blockedOn)
// Process channels in parallel for better performance
prCtx := prContext{
Owner: owner,
Repo: repo,
Number: prNumber,
State: prState,
Event: event,
CheckRes: checkResult,
}
taggedUsers := c.processChannelsInParallel(ctx, prCtx, channels, workspaceID)
// Handle user notifications - send DMs to blocked users
// Logic:
// - If channels were notified (taggedUsers not empty): Only send DMs to those successfully tagged Slack users
// - If no channels were notified (taggedUsers empty/nil): Attempt DMs to all blocked GitHub users
if len(blockedOn) > 0 {
if len(taggedUsers) > 0 {
// Channels were notified - only send DMs to successfully tagged Slack users
slog.Info("preparing to send DM notifications to users tagged in channels",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"total_blocked_github_users", len(blockedOn),
"successfully_tagged_slack_users", len(taggedUsers),
"will_send_async", true,
"dm_logic", "immediate if not in channel, delayed if in channel")
// Send DMs asynchronously to avoid blocking event processing
// SECURITY NOTE: Use detached context to allow graceful completion of DM notifications
// even if parent context is cancelled during shutdown. Operations are still bounded by
// explicit 60-second timeout for DM delivery (~1s each).
// Note: No panic recovery - we want panics to propagate and restart the service (Cloud Run will handle it)
// A quiet failure is worse than a visible crash that triggers automatic recovery
dmCtx, dmCancel := context.WithTimeout(context.WithoutCancel(ctx), 60*time.Second)
go func() {
defer dmCancel()
c.sendDMNotificationsToSlackUsers(dmCtx, workspaceID, owner, repo, prNumber, taggedUsers, event, prState, checkResult)
}()
} else {
// No channels were notified - attempt to send immediate DMs to all blocked GitHub users
// Deduplicate blocked users (same user might be blocked for multiple reasons)
uniqueGitHubUsers := make(map[string]bool)
for _, githubUser := range blockedOn {
uniqueGitHubUsers[githubUser] = true
}
slog.Info("preparing to send immediate DMs (no channels were notified)",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"total_blocked_github_users", len(blockedOn),
"unique_github_users", len(uniqueGitHubUsers),
"will_send_async", true,
"warning", "DMs are sent async - if instance crashes before completion, another instance may retry and send duplicates")
// Send DMs asynchronously to avoid blocking event processing
// SECURITY NOTE: Use detached context to allow graceful completion of DM notifications
// even if parent context is cancelled during shutdown. Operations are still bounded by
// explicit 60-second timeout, allowing time for:
// - GitHub email lookup via gh-mailto (~5-10s with retries/timeouts)
// - Slack API user lookup for multiple guesses (~5-15s total)
// - DM delivery (~1s)
// This generous timeout prevents premature cancellation while still ensuring
// eventual completion during shutdown. Most requests complete in <10s.
// Note: No panic recovery - we want panics to propagate and restart the service (Cloud Run will handle it)
// A quiet failure is worse than a visible crash that triggers automatic recovery
dmCtx, dmCancel := context.WithTimeout(context.WithoutCancel(ctx), 60*time.Second)
go func() {
defer dmCancel()
c.sendDMNotificationsToGitHubUsers(dmCtx, workspaceID, owner, repo, prNumber, uniqueGitHubUsers, event, prState, checkResult)
}()
}
} else {
slog.Info("no users blocking PR - no notifications needed",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"pr_state", prState)
}
}
// sendDMNotificationsToSlackUsers sends DM notifications to Slack users who were tagged in channels.
// This runs in a separate goroutine to avoid blocking event processing.
// Uses Slack user IDs directly (no GitHub->Slack mapping needed).
//
//nolint:revive // parameter count required for complete context
func (c *Coordinator) sendDMNotificationsToSlackUsers(
ctx context.Context, workspaceID, owner, repo string,
prNumber int, slackUsers map[string]bool,
event struct {
Action string `json:"action"`
PullRequest struct {
HTMLURL string `json:"html_url"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
User struct {
Login string `json:"login"`
} `json:"user"`
Number int `json:"number"`
} `json:"pull_request"`
Number int `json:"number"`
},
prState string,
checkResult *turn.CheckResponse,
) {
slog.Info("starting DM notification batch for tagged Slack users",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"workspace", workspaceID,
"user_count", len(slackUsers),
"pr_state", prState)
sentCount := 0
failedCount := 0
for slackUserID := range slackUsers {
// Get tag info to determine which channel the user was tagged in
tagInfo := c.notifier.Tracker.LastUserPRChannelTag(workspaceID, slackUserID, owner, repo, prNumber)
// For channel name lookup (needed for config), we need to resolve the channel ID back to name
// This is optional - if we can't resolve it, NotifyUser will use defaults
var channelName string
if tagInfo.ChannelID != "" {
// We don't have a reverse lookup, so just pass empty string
// NotifyUser will use default delay if channelName is empty
channelName = ""
}
// Send notification using smart delay logic
prInfo := notify.PRInfo{
Owner: owner,
Repo: repo,
Number: prNumber,
Title: event.PullRequest.Title,
Author: event.PullRequest.User.Login,
State: prState,
HTMLURL: event.PullRequest.HTMLURL,
}
// Add workflow state and next actions if available
if checkResult != nil {
prInfo.WorkflowState = checkResult.Analysis.WorkflowState
prInfo.NextAction = checkResult.Analysis.NextAction
}
err := c.notifier.NotifyUser(ctx, workspaceID, slackUserID, tagInfo.ChannelID, channelName, prInfo)
if err != nil {
slog.Warn("failed to notify user",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"slack_user", slackUserID,
"error", err)
failedCount++
} else {
sentCount++
}
}
slog.Info("completed DM notification batch for tagged Slack users",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"workspace", workspaceID,
"sent_count", sentCount,
"failed_count", failedCount,
"total_users", len(slackUsers))
}
// sendDMNotificationsToGitHubUsers sends immediate DM notifications to blocked GitHub users.
// This runs in a separate goroutine to avoid blocking event processing.
// Used when no channels were notified (performs GitHub->Slack mapping).
//
//nolint:revive // parameter count required for complete context
func (c *Coordinator) sendDMNotificationsToGitHubUsers(
ctx context.Context, workspaceID, owner, repo string,
prNumber int, uniqueUsers map[string]bool,
event struct {
Action string `json:"action"`
PullRequest struct {
HTMLURL string `json:"html_url"`
Title string `json:"title"`
CreatedAt time.Time `json:"created_at"`
User struct {
Login string `json:"login"`
} `json:"user"`
Number int `json:"number"`
} `json:"pull_request"`
Number int `json:"number"`
},
prState string,
checkResult *turn.CheckResponse,
) {
slog.Info("starting immediate DM notification batch (no channels were notified)",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"workspace", workspaceID,
"github_user_count", len(uniqueUsers),
"pr_state", prState,
"note", "will attempt GitHub->Slack mapping for each user")
domain := c.configManager.Domain(owner)
sentCount := 0
failedCount := 0
mappingFailures := 0
for githubUser := range uniqueUsers {
// Map GitHub username to Slack user ID
slackUserID, err := c.userMapper.SlackHandle(ctx, githubUser, owner, domain)
if err != nil || slackUserID == "" {
slog.Info("could not map GitHub user to Slack - skipping immediate DM",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"github_user", githubUser,
"error", err,
"impact", "user will not receive DM notification")
mappingFailures++
continue
}
// Send immediate DM (no channel tag delay logic since no channels were notified)
prInfo := notify.PRInfo{
Owner: owner,
Repo: repo,
Number: prNumber,
Title: event.PullRequest.Title,
Author: event.PullRequest.User.Login,
State: prState,
HTMLURL: event.PullRequest.HTMLURL,
}
// Add workflow state and next actions if available
if checkResult != nil {
prInfo.WorkflowState = checkResult.Analysis.WorkflowState
prInfo.NextAction = checkResult.Analysis.NextAction
}
// Send immediate DM (pass empty channelID and channelName since no channels were notified)
err = c.notifier.NotifyUser(ctx, workspaceID, slackUserID, "", "", prInfo)
if err != nil {
slog.Warn("failed to send immediate DM",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"github_user", githubUser,
"slack_user", slackUserID,
"error", err)
failedCount++
} else {
sentCount++
}
}
slog.Info("completed immediate DM notification batch (no channels were notified)",
logFieldPR, fmt.Sprintf(prFormatString, owner, repo, prNumber),
"workspace", workspaceID,
"sent_count", sentCount,
"failed_count", failedCount,
"mapping_failures", mappingFailures,
"total_github_users", len(uniqueUsers))
}
// extractStateFromTurnclient extracts PR state from turnclient response without additional API calls.
func (*Coordinator) extractStateFromTurnclient(checkResult *turn.CheckResponse) string {
// Use turnclient's state analysis instead of making GitHub API calls
// This maps turnclient states to our emoji reactions
pr := checkResult.PullRequest
analysis := checkResult.Analysis
slog.Debug("extracting state from turnclient data",
"pr_state", pr.State,