gunk-dev/the-valley

server.go

source4cbb5ec9c5dbmain's published tip history
8.8 KiB
1package webhook
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "net"
8 "net/http"
9)
10
11// Event is an invalidation signal from a GitHub webhook. It carries just
12// enough information to know which PR (or repo) needs a fresh status fetch.
13// The dashboard uses this to trigger an immediate re-fetch via the same
14// code path that polling uses, rather than constructing status from the
15// webhook payload directly.
16type Event struct {
17 PRNumber string // PR number, e.g. "42"; empty for repo-wide events (e.g. push)
18 Repo string // owner/repo
19 EventType string // "check_run", "check_suite", "pull_request", "pull_request_review", "issue_comment", "push"
20}
21
22// Server is an HTTP server that receives GitHub webhook payloads from a relay
23// and sends parsed events on a channel.
24type Server struct {
25 port int
26 path string
27 events chan<- Event
28 srv *http.Server
29 listener net.Listener
30}
31
32// NewServer creates a webhook server that sends parsed events to the given channel.
33func NewServer(port int, path string, events chan<- Event) *Server {
34 if path == "" {
35 path = "/webhook/github"
36 }
37 return &Server{
38 port: port,
39 path: path,
40 events: events,
41 }
42}
43
44// Addr returns the listener address once the server is started. Returns ""
45// if the server hasn't started yet.
46func (s *Server) Addr() string {
47 if s.listener != nil {
48 return s.listener.Addr().String()
49 }
50 return ""
51}
52
53// Listen binds the server to its port. Call this before Serve so the
54// listener address is available without a data race.
55func (s *Server) Listen() error {
56 mux := http.NewServeMux()
57 mux.HandleFunc(s.path, s.handleWebhook)
58
59 s.srv = &http.Server{
60 Handler: mux,
61 }
62
63 ln, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", s.port))
64 if err != nil {
65 return fmt.Errorf("webhook server listen: %w", err)
66 }
67 s.listener = ln
68 return nil
69}
70
71// Serve starts accepting connections on the already-bound listener.
72// It blocks until the server is shut down. Listen must be called first.
73func (s *Server) Serve() error {
74 if s.listener == nil {
75 return fmt.Errorf("webhook server: Listen must be called before Serve")
76 }
77 return s.srv.Serve(s.listener)
78}
79
80// Start binds the listener and serves. It blocks until the server is shut down.
81func (s *Server) Start() error {
82 if err := s.Listen(); err != nil {
83 return err
84 }
85 return s.Serve()
86}
87
88// Shutdown gracefully stops the server.
89func (s *Server) Shutdown(ctx context.Context) error {
90 if s.srv != nil {
91 return s.srv.Shutdown(ctx)
92 }
93 return nil
94}
95
96func (s *Server) handleWebhook(w http.ResponseWriter, r *http.Request) {
97 if r.Method != http.MethodPost {
98 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
99 return
100 }
101 defer r.Body.Close()
102
103 eventType := r.Header.Get("X-GitHub-Event")
104 if eventType == "" {
105 http.Error(w, "missing X-GitHub-Event header", http.StatusBadRequest)
106 return
107 }
108
109 var payload json.RawMessage
110 if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
111 http.Error(w, "invalid JSON", http.StatusBadRequest)
112 return
113 }
114
115 events := parseEvent(eventType, payload)
116 for _, ev := range events {
117 select {
118 case s.events <- ev:
119 default:
120 // Drop event if channel is full to avoid blocking the HTTP handler.
121 }
122 }
123
124 w.WriteHeader(http.StatusOK)
125}
126
127// parseEvent dispatches to the appropriate parser based on event type.
128func parseEvent(eventType string, payload json.RawMessage) []Event {
129 switch eventType {
130 case "check_run":
131 return parseCheckRun(payload)
132 case "check_suite":
133 return parseCheckSuite(payload)
134 case "pull_request":
135 return parsePullRequest(payload)
136 case "pull_request_review":
137 return parsePullRequestReview(payload)
138 case "issue_comment":
139 return parseIssueComment(payload)
140 case "push":
141 return parsePush(payload)
142 default:
143 return nil
144 }
145}
146
147// GitHub webhook payload structures (only the fields we need).
148
149type checkRunPayload struct {
150 Action string `json:"action"`
151 CheckRun struct {
152 Conclusion string `json:"conclusion"`
153 PullRequests []struct {
154 Number int `json:"number"`
155 } `json:"pull_requests"`
156 } `json:"check_run"`
157 Repository repoPayload `json:"repository"`
158}
159
160type checkSuitePayload struct {
161 Action string `json:"action"`
162 CheckSuite struct {
163 Conclusion string `json:"conclusion"`
164 PullRequests []struct {
165 Number int `json:"number"`
166 } `json:"pull_requests"`
167 } `json:"check_suite"`
168 Repository repoPayload `json:"repository"`
169}
170
171type pullRequestPayload struct {
172 Action string `json:"action"`
173 PullRequest struct {
174 Number int `json:"number"`
175 State string `json:"state"`
176 Merged bool `json:"merged"`
177 Mergeable *bool `json:"mergeable"`
178 MergeableState string `json:"mergeable_state"`
179 } `json:"pull_request"`
180 Repository repoPayload `json:"repository"`
181}
182
183type pullRequestReviewPayload struct {
184 Action string `json:"action"`
185 Review struct {
186 State string `json:"state"`
187 } `json:"review"`
188 PullRequest struct {
189 Number int `json:"number"`
190 } `json:"pull_request"`
191 Repository repoPayload `json:"repository"`
192}
193
194type issueCommentPayload struct {
195 Action string `json:"action"`
196 Issue struct {
197 Number int `json:"number"`
198 PullRequest *json.RawMessage `json:"pull_request"`
199 } `json:"issue"`
200 Repository repoPayload `json:"repository"`
201}
202
203type pushPayload struct {
204 Ref string `json:"ref"`
205 Repository repoPayload `json:"repository"`
206}
207
208type repoPayload struct {
209 FullName string `json:"full_name"`
210 DefaultBranch string `json:"default_branch"`
211}
212
213func parseCheckRun(payload json.RawMessage) []Event {
214 var p checkRunPayload
215 if err := json.Unmarshal(payload, &p); err != nil {
216 return nil
217 }
218 if p.Action != "completed" {
219 return nil
220 }
221
222 var events []Event
223 for _, pr := range p.CheckRun.PullRequests {
224 events = append(events, Event{
225 PRNumber: fmt.Sprintf("%d", pr.Number),
226 Repo: p.Repository.FullName,
227 EventType: "check_run",
228 })
229 }
230 return events
231}
232
233func parseCheckSuite(payload json.RawMessage) []Event {
234 var p checkSuitePayload
235 if err := json.Unmarshal(payload, &p); err != nil {
236 return nil
237 }
238 if p.Action != "completed" {
239 return nil
240 }
241
242 var events []Event
243 for _, pr := range p.CheckSuite.PullRequests {
244 events = append(events, Event{
245 PRNumber: fmt.Sprintf("%d", pr.Number),
246 Repo: p.Repository.FullName,
247 EventType: "check_suite",
248 })
249 }
250 return events
251}
252
253func parsePullRequest(payload json.RawMessage) []Event {
254 var p pullRequestPayload
255 if err := json.Unmarshal(payload, &p); err != nil {
256 return nil
257 }
258
259 switch p.Action {
260 case "opened", "synchronize", "closed", "reopened", "merged":
261 // valid actions
262 default:
263 return nil
264 }
265
266 return []Event{{
267 PRNumber: fmt.Sprintf("%d", p.PullRequest.Number),
268 Repo: p.Repository.FullName,
269 EventType: "pull_request",
270 }}
271}
272
273func parsePullRequestReview(payload json.RawMessage) []Event {
274 var p pullRequestReviewPayload
275 if err := json.Unmarshal(payload, &p); err != nil {
276 return nil
277 }
278 if p.Action != "submitted" {
279 return nil
280 }
281
282 // Emit for any submitted review regardless of state (approved,
283 // changes_requested, commented). Webhooks are invalidation signals; the
284 // trusted-reviewer + review-time/commit-time filtering lives in the
285 // detection layer (hasUnaddressedTrustedComments), not here. Dropping
286 // "commented" reviews stranded trusted-reviewer comments on quiescent
287 // PRs (see issue #271). We only ignore non-"submitted" actions
288 // (e.g. "edited", "dismissed").
289
290 return []Event{{
291 PRNumber: fmt.Sprintf("%d", p.PullRequest.Number),
292 Repo: p.Repository.FullName,
293 EventType: "pull_request_review",
294 }}
295}
296
297func parseIssueComment(payload json.RawMessage) []Event {
298 var p issueCommentPayload
299 if err := json.Unmarshal(payload, &p); err != nil {
300 return nil
301 }
302 // Created and edited comments both count: a trusted reviewer may edit an
303 // older comment to add feedback, and detection watermarks conversation
304 // comments on updated_at. Deletions are ignored. GitHub sends issue_comment
305 // for plain issues too; only an issue carrying a pull_request object is a
306 // PR conversation comment.
307 if p.Action != "created" && p.Action != "edited" {
308 return nil
309 }
310 if p.Issue.PullRequest == nil {
311 return nil
312 }
313
314 // Like pull_request_review, this is only an invalidation signal: the
315 // trusted-reviewer and commit-time filtering of conversation comments
316 // lives in hasUnaddressedTrustedComments.
317 return []Event{{
318 PRNumber: fmt.Sprintf("%d", p.Issue.Number),
319 Repo: p.Repository.FullName,
320 EventType: "issue_comment",
321 }}
322}
323
324func parsePush(payload json.RawMessage) []Event {
325 var p pushPayload
326 if err := json.Unmarshal(payload, &p); err != nil {
327 return nil
328 }
329
330 // Only care about pushes to the default branch
331 defaultRef := "refs/heads/" + p.Repository.DefaultBranch
332 if p.Ref != defaultRef {
333 return nil
334 }
335
336 // Signal that the base branch changed — PRs may have new conflicts.
337 // PRNumber is empty to indicate this is a repo-wide event.
338 return []Event{{
339 Repo: p.Repository.FullName,
340 EventType: "push",
341 }}
342}
343