Skip to content

Commit 9171e63

Browse files
authored
Merge pull request #15223 from cli/babakks/event-hint-feature-detection
Show `gh event listen` hints only when event subscriptions are enabled
2 parents fb00869 + 30c6d78 commit 9171e63

39 files changed

Lines changed: 456 additions & 81 deletions

‎api/client.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const (
2020
apiVersionValue = "2022-11-28"
2121
authorization = "Authorization"
2222
cacheTTL = "X-GH-CACHE-TTL"
23+
cacheStatuses = "X-GH-CACHE-STATUSES"
2324
graphqlFeatures = "GraphQL-Features"
2425
features = "merge_queue"
2526
userAgent = "User-Agent"

‎api/http_client.go‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"io"
77
"net/http"
88
"net/url"
9+
"strconv"
910
"strings"
1011
"time"
1112

@@ -189,6 +190,32 @@ func NewCachedHTTPClient(httpClient *http.Client, ttl time.Duration) *http.Clien
189190
return &newClient
190191
}
191192

193+
// NewCachedHTTPClientWithStatuses is like NewCachedHTTPClient, but it also caches responses with the given status
194+
// codes, such as 403, which are not cached by default.
195+
func NewCachedHTTPClientWithStatuses(httpClient *http.Client, ttl time.Duration, statuses ...int) *http.Client {
196+
newClient := NewCachedHTTPClient(httpClient, ttl)
197+
newClient.Transport = addCacheStatusesHeader(newClient.Transport, statuses...)
198+
return newClient
199+
}
200+
201+
func addCacheStatusesHeader(rt http.RoundTripper, statuses ...int) http.RoundTripper {
202+
if len(statuses) == 0 {
203+
return rt
204+
}
205+
values := make([]string, len(statuses))
206+
for i, status := range statuses {
207+
values[i] = strconv.Itoa(status)
208+
}
209+
value := strings.Join(values, ",")
210+
return &funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {
211+
// If the header is already set in the request, don't overwrite it.
212+
if req.Header.Get(cacheStatuses) == "" {
213+
req.Header.Set(cacheStatuses, value)
214+
}
215+
return rt.RoundTrip(req)
216+
}}
217+
}
218+
192219
// AddCacheTTLHeader adds a header to the request telling the cache that the request
193220
// should be cached for a specified amount of time.
194221
func AddCacheTTLHeader(rt http.RoundTripper, ttl time.Duration) http.RoundTripper {

‎api/http_client_test.go‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"regexp"
1313
"strings"
1414
"testing"
15+
"time"
1516

1617
"github.com/MakeNowJust/heredoc"
1718
"github.com/cli/cli/v2/pkg/auth"
@@ -724,3 +725,45 @@ func normalizeVerboseLog(t string) string {
724725
t = timezoneRE.ReplaceAllString(t, "> Time-Zone: <timezone>")
725726
return t
726727
}
728+
729+
func TestNewCachedHTTPClientWithStatuses(t *testing.T) {
730+
tests := []struct {
731+
name string
732+
statuses []int
733+
wantStatuses string
734+
}{
735+
{
736+
name: "with statuses",
737+
statuses: []int{http.StatusForbidden, http.StatusNotFound},
738+
wantStatuses: "403,404",
739+
},
740+
{
741+
name: "without statuses",
742+
wantStatuses: "",
743+
},
744+
}
745+
746+
for _, tt := range tests {
747+
t.Run(tt.name, func(t *testing.T) {
748+
var gotHeader http.Header
749+
httpClient := &http.Client{Transport: funcTripper{roundTrip: func(req *http.Request) (*http.Response, error) {
750+
gotHeader = req.Header
751+
return &http.Response{StatusCode: http.StatusOK, Body: http.NoBody, Request: req}, nil
752+
}}}
753+
754+
client := NewCachedHTTPClientWithStatuses(httpClient, time.Hour, tt.statuses...)
755+
res, err := client.Get("https://api.github.com/user")
756+
require.NoError(t, err)
757+
res.Body.Close()
758+
759+
assert.Equal(t, "1h0m0s", gotHeader.Get("X-GH-CACHE-TTL"))
760+
if tt.wantStatuses != "" {
761+
assert.Equal(t, tt.wantStatuses, gotHeader.Get("X-GH-CACHE-STATUSES"))
762+
} else {
763+
// We can't use the Get method because it'll return the same value for both empty and non-existent
764+
// headers and we want to make sure the header is actually not present.
765+
assert.Empty(t, gotHeader.Values("X-GH-CACHE-STATUSES"))
766+
}
767+
})
768+
}
769+
}

‎docs/event-listen-preview.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ When `internal/agents` detects an agent caller, a successful `gh pr create` of a
4343

4444
For an agent caller, `gh run watch` and `gh run view` of a workflow run that is not completed and belongs to a github.com pull request print a similar hint on stderr, addressed to agents that need to wait for the checks of the pull request to finish. It suggests listening to `com.github.pull_request.check_suite.status.changed.v1` for the pull request, with the same notes, except that it explains that each check suite sends its own event with its conclusion, and that the checks should be read with `gh pr checks` after each event, running the listener again while any are pending. `gh run watch` prints it before it starts watching, so it is seen even if the watch is stopped. `gh run view` prints it with `--json` too, but not with `--web` or `--log`. The `gh run watch` and `gh run view` help texts point to `gh event listen` for waiting on the workflow runs of a github.com pull request.
4545

46+
Hints are only printed on github.com if event subscriptions are enabled for the account. GitHub Enterprise Server and GHE.com hosts skip the probe and print no hint. Feature detection checks this with `GET /event-subscriptions?per_page=1` and a `gh-feature-detection: true` header, which marks the request as a probe. A `403` or `404` response means event subscriptions are not enabled, and other failures print no hint. The result, including a `403` or `404`, is cached for 24 hours.
47+
4648
## Eval use
4749

4850
The shipped `gh` skill at `skills/gh` documents `gh event listen`. Evaluate it from the working tree, or compare it with the version on trunk, which has no event guidance until this change merges:

‎go.mod‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ require (
1818
github.com/cenkalti/backoff/v4 v4.3.0
1919
github.com/cenkalti/backoff/v5 v5.0.3
2020
github.com/charmbracelet/x/ansi v0.12.0
21-
github.com/cli/go-gh/v2 v2.17.0
21+
github.com/cli/go-gh/v2 v2.17.1
2222
github.com/cli/go-internal v0.0.0-20241025142207-6c48bcd5ce24
2323
github.com/cli/oauth v1.3.0
2424
github.com/cli/safeexec v1.0.1
@@ -128,8 +128,8 @@ require (
128128
github.com/huandu/xstrings v1.5.0 // indirect
129129
github.com/in-toto/in-toto-golang v0.11.0 // indirect
130130
github.com/inconshreveable/mousetrap v1.1.0 // indirect
131-
github.com/itchyny/gojq v0.12.19 // indirect
132-
github.com/itchyny/timefmt-go v0.1.8 // indirect
131+
github.com/itchyny/gojq v0.12.20 // indirect
132+
github.com/itchyny/timefmt-go v0.1.9 // indirect
133133
github.com/jedisct1/go-minisign v0.0.0-20241212093149-d2f9f49435c7 // indirect
134134
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
135135
github.com/mattn/go-runewidth v0.0.31 // indirect

‎go.sum‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,8 @@ github.com/charmbracelet/x/xpty v0.1.3 h1:eGSitii4suhzrISYH50ZfufV3v085BXQwIytcO
140140
github.com/charmbracelet/x/xpty v0.1.3/go.mod h1:poPYpWuLDBFCKmKLDnhBp51ATa0ooD8FhypRwEFtH3Y=
141141
github.com/cli/browser v1.3.0 h1:LejqCrpWr+1pRqmEPDGnTZOjsMe7sehifLynZJuqJpo=
142142
github.com/cli/browser v1.3.0/go.mod h1:HH8s+fOAxjhQoBUAsKuPCbqUuxZDhQ2/aD+SzsEfBTk=
143-
github.com/cli/go-gh/v2 v2.17.0 h1:F24s1Ow/6pgWO0FXXSTi7l4YLkcuS94XPv7npEGkrQc=
144-
github.com/cli/go-gh/v2 v2.17.0/go.mod h1:bc2VCe0OUSOuhDz5HeQrA7RAtc/d3PtyGogBXHbcp1o=
143+
github.com/cli/go-gh/v2 v2.17.1 h1:1LwJphY4Y5j2C5Q1u6X6vviSJny4bz/x2ALfVSmkJ0A=
144+
github.com/cli/go-gh/v2 v2.17.1/go.mod h1:MjKeGWcbG8rjtpudZB8HVN2X8a0xOyNY4nAg6vkSr/c=
145145
github.com/cli/go-internal v0.0.0-20241025142207-6c48bcd5ce24 h1:QDrhR4JA2n3ij9YQN0u5ZeuvRIIvsUGmf5yPlTS0w8E=
146146
github.com/cli/go-internal v0.0.0-20241025142207-6c48bcd5ce24/go.mod h1:rr9GNING0onuVw8MnracQHn7PcchnFlP882Y0II2KZk=
147147
github.com/cli/oauth v1.3.0 h1:n+g95m4ht5dAlG1XGMcIT+oU+dbJZVr80fuOf5lOHUM=
@@ -327,10 +327,10 @@ github.com/in-toto/in-toto-golang v0.11.0 h1:nfidMYBFx+E0lnmX5KUnN2Pdm8zdNKal1ay
327327
github.com/in-toto/in-toto-golang v0.11.0/go.mod h1:u3PjTnwFKjp5a1YCcw8SJg0G+tMeKfVoWsWeFMDCMtw=
328328
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
329329
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
330-
github.com/itchyny/gojq v0.12.19 h1:ttXA0XCLEMoaLOz5lSeFOZ6u6Q3QxmG46vfgI4O0DEs=
331-
github.com/itchyny/gojq v0.12.19/go.mod h1:5galtVPDywX8SPSOrqjGxkBeDhSxEW1gSxoy7tn1iZY=
332-
github.com/itchyny/timefmt-go v0.1.8 h1:1YEo1JvfXeAHKdjelbYr/uCuhkybaHCeTkH8Bo791OI=
333-
github.com/itchyny/timefmt-go v0.1.8/go.mod h1:5E46Q+zj7vbTgWY8o5YkMeYb4I6GeWLFnetPy5oBrAI=
330+
github.com/itchyny/gojq v0.12.20 h1:mvxzKjEJDfeLlPc/15q5Kf6wLtEW2T399BL8xmOd9EQ=
331+
github.com/itchyny/gojq v0.12.20/go.mod h1:cgT47OXUC/BWCBh9V4LuuTRSwFIJNR5loUyqlzbIJbw=
332+
github.com/itchyny/timefmt-go v0.1.9 h1:J4j1qMqZbg5jycwT6zIKfRgZ9aqqMxqanaI6Rr9Ezs8=
333+
github.com/itchyny/timefmt-go v0.1.9/go.mod h1:5E46Q+zj7vbTgWY8o5YkMeYb4I6GeWLFnetPy5oBrAI=
334334
github.com/jedisct1/go-minisign v0.0.0-20241212093149-d2f9f49435c7 h1:FWpSWRD8FbVkKQu8M1DM9jF5oXFLyE+XpisIYfdzbic=
335335
github.com/jedisct1/go-minisign v0.0.0-20241212093149-d2f9f49435c7/go.mod h1:BMxO138bOokdgt4UaxZiEfypcSHX0t6SIFimVP1oRfk=
336336
github.com/jellydator/ttlcache/v3 v3.4.1 h1:bOdXmXiycyK6E6Qjyuj5vl+/vU3SCOoDs8a86NbHjAQ=

‎internal/featuredetection/detector_mock.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ func (md *DisabledDetectorMock) AuthFeatures() (AuthFeatures, error) {
4040
return AuthFeatures{}, nil
4141
}
4242

43+
func (md *DisabledDetectorMock) EventsFeatures() (EventsFeatures, error) {
44+
return EventsFeatures{}, nil
45+
}
46+
4347
type EnabledDetectorMock struct{}
4448

4549
func (md *EnabledDetectorMock) IssueFeatures() (IssueFeatures, error) {
@@ -82,6 +86,10 @@ func (md *EnabledDetectorMock) AuthFeatures() (AuthFeatures, error) {
8286
return AuthFeatures{ExpiringTokens: true}, nil
8387
}
8488

89+
func (md *EnabledDetectorMock) EventsFeatures() (EventsFeatures, error) {
90+
return EventsFeatures{Subscriptions: true}, nil
91+
}
92+
8593
type AdvancedIssueSearchDetectorMock struct {
8694
EnabledDetectorMock
8795
searchFeatures SearchFeatures

‎internal/featuredetection/feature_detection.go‎

Lines changed: 77 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
package featuredetection
22

33
import (
4+
"context"
5+
"errors"
46
"net/http"
7+
"time"
58

69
"github.com/cli/cli/v2/api"
710
"github.com/cli/cli/v2/internal/gh"
@@ -22,6 +25,7 @@ type Detector interface {
2225
ReleaseFeatures() (ReleaseFeatures, error)
2326
ActionsFeatures() (ActionsFeatures, error)
2427
AuthFeatures() (AuthFeatures, error)
28+
EventsFeatures() (EventsFeatures, error)
2529
}
2630

2731
type IssueFeatures struct {
@@ -182,9 +186,18 @@ type AuthFeatures struct {
182186
ExpiringTokens bool
183187
}
184188

189+
// EventsFeatures describes the access of the authenticated account to the Event Streams API.
190+
type EventsFeatures struct {
191+
// TODO eventSubscriptionsPreviewCleanup - revisit once event subscriptions are generally available.
192+
// Subscriptions indicates whether event subscriptions are enabled for the account. While in preview, they are only
193+
// available on github.com, and only to accounts they are enabled for.
194+
Subscriptions bool
195+
}
196+
185197
type detector struct {
186198
host string
187199
httpClient *http.Client
200+
cacheTTL time.Duration
188201
}
189202

190203
func NewDetector(httpClient *http.Client, host string) Detector {
@@ -194,6 +207,24 @@ func NewDetector(httpClient *http.Client, host string) Detector {
194207
}
195208
}
196209

210+
// NewCachedDetector returns a Detector that probes the given host and caches detection results for the given TTL.
211+
func NewCachedDetector(httpClient *http.Client, host string, ttl time.Duration) Detector {
212+
return &detector{
213+
httpClient: httpClient,
214+
host: host,
215+
cacheTTL: ttl,
216+
}
217+
}
218+
219+
// client returns the HTTP client for detection requests. If the detector caches results, the client also caches
220+
// responses with the given extra status codes, which are not cached by default.
221+
func (d *detector) client(extraStatuses ...int) *http.Client {
222+
if d.cacheTTL <= 0 {
223+
return d.httpClient
224+
}
225+
return api.NewCachedHTTPClientWithStatuses(d.httpClient, d.cacheTTL, extraStatuses...)
226+
}
227+
197228
func (d *detector) IssueFeatures() (IssueFeatures, error) {
198229
if !ghauth.IsEnterprise(d.host) {
199230
return allIssueFeatures, nil
@@ -214,7 +245,7 @@ func (d *detector) IssueFeatures() (IssueFeatures, error) {
214245
} `graphql:"Issue: __type(name: \"Issue\")"`
215246
}
216247

217-
gql := api.NewClientFromHTTP(d.httpClient)
248+
gql := api.NewClientFromHTTP(d.client())
218249
err := gql.Query(d.host, "Issue_fields", &featureDetection, nil)
219250
if err != nil {
220251
return IssueFeatures{}, err
@@ -261,7 +292,7 @@ func (d *detector) PullRequestFeatures() (PullRequestFeatures, error) {
261292
} `graphql:"WorkflowRun: __type(name: \"WorkflowRun\")"`
262293
}
263294

264-
gql := api.NewClientFromHTTP(d.httpClient)
295+
gql := api.NewClientFromHTTP(d.client())
265296

266297
var wg errgroup.Group
267298
wg.Go(func() error {
@@ -314,7 +345,7 @@ func (d *detector) RepositoryFeatures() (RepositoryFeatures, error) {
314345
} `graphql:"Repository: __type(name: \"Repository\")"`
315346
}
316347

317-
gql := api.NewClientFromHTTP(d.httpClient)
348+
gql := api.NewClientFromHTTP(d.client())
318349

319350
err := gql.Query(d.host, "Repository_fields", &featureDetection, nil)
320351
if err != nil {
@@ -345,7 +376,7 @@ func (d *detector) ProjectsV1() gh.ProjectsV1Support {
345376
return gh.ProjectsV1Unsupported
346377
}
347378

348-
hostVersion, hostVersionErr := resolveEnterpriseVersion(d.httpClient, d.host)
379+
hostVersion, hostVersionErr := resolveEnterpriseVersion(d.client(), d.host)
349380
v1ProjectCutoffVersion, v1ProjectCutoffVersionErr := version.NewVersion(enterpriseProjectsV1Removed)
350381

351382
if hostVersionErr == nil && v1ProjectCutoffVersionErr == nil && hostVersion.LessThan(v1ProjectCutoffVersion) {
@@ -373,7 +404,7 @@ func (d *detector) ProjectFeatures() (ProjectFeatures, error) {
373404
} `graphql:"ProjectV2: __type(name: \"ProjectV2\")"`
374405
}
375406

376-
gql := api.NewClientFromHTTP(d.httpClient)
407+
gql := api.NewClientFromHTTP(d.client())
377408
err := gql.Query(d.host, "ProjectV2_fields", &featureDetection, nil)
378409
if err != nil {
379410
return features, err
@@ -434,7 +465,7 @@ func (d *detector) SearchFeatures() (SearchFeatures, error) {
434465
return SearchFeatures{}, err
435466
}
436467

437-
hostVersion, err := resolveEnterpriseVersion(d.httpClient, d.host)
468+
hostVersion, err := resolveEnterpriseVersion(d.client(), d.host)
438469
if err != nil {
439470
return SearchFeatures{}, err
440471
}
@@ -472,7 +503,7 @@ func (d *detector) SearchFeatures() (SearchFeatures, error) {
472503
} `graphql:"SearchType: __type(name: \"SearchType\")"`
473504
}
474505

475-
gql := api.NewClientFromHTTP(d.httpClient)
506+
gql := api.NewClientFromHTTP(d.client())
476507
if err := gql.Query(d.host, "SearchType_enumValues", &searchTypeFeatureDetection, nil); err != nil {
477508
return SearchFeatures{}, err
478509
}
@@ -511,7 +542,7 @@ func (d *detector) ReleaseFeatures() (ReleaseFeatures, error) {
511542
} `graphql:"Release: __type(name: \"Release\")"`
512543
}
513544

514-
gql := api.NewClientFromHTTP(d.httpClient)
545+
gql := api.NewClientFromHTTP(d.client())
515546
if err := gql.Query(d.host, "Release_fields", &releaseFeatureDetection, nil); err != nil {
516547
return ReleaseFeatures{}, err
517548
}
@@ -559,7 +590,7 @@ func (d *detector) ActionsFeatures() (ActionsFeatures, error) {
559590
return ActionsFeatures{}, err
560591
}
561592

562-
hostVersion, err := resolveEnterpriseVersion(d.httpClient, d.host)
593+
hostVersion, err := resolveEnterpriseVersion(d.client(), d.host)
563594
if err != nil {
564595
return ActionsFeatures{}, err
565596
}
@@ -581,7 +612,7 @@ func (d *detector) AuthFeatures() (AuthFeatures, error) {
581612
return AuthFeatures{ExpiringTokens: true}, nil
582613
}
583614

584-
hostVersion, err := resolveEnterpriseVersion(d.httpClient, d.host)
615+
hostVersion, err := resolveEnterpriseVersion(d.client(), d.host)
585616
if err != nil {
586617
return AuthFeatures{}, err
587618
}
@@ -591,6 +622,42 @@ func (d *detector) AuthFeatures() (AuthFeatures, error) {
591622
}, nil
592623
}
593624

625+
const eventsFeatureDetectionTimeout = 3 * time.Second
626+
627+
// EventsFeatures checks whether event subscriptions are enabled for the authenticated account. Only github.com is
628+
// supported, so GitHub Enterprise Server and GHE.com hosts report unavailable without making a request. A 403 response
629+
// means they are not enabled for the account, and a 404 response means the host does not have the endpoint at all. Both
630+
// are cached like a successful response when the detector caches results.
631+
func (d *detector) EventsFeatures() (EventsFeatures, error) {
632+
if ghauth.IsEnterprise(d.host) || ghauth.IsTenancy(d.host) {
633+
return EventsFeatures{}, nil
634+
}
635+
636+
u, err := safeurl.JoinPath("event-subscriptions")
637+
if err != nil {
638+
return EventsFeatures{}, err
639+
}
640+
u.SetQuery("per_page", "1")
641+
642+
ctx, cancel := context.WithTimeout(context.Background(), eventsFeatureDetectionTimeout)
643+
defer cancel()
644+
client := api.NewClientFromHTTP(d.client(http.StatusForbidden, http.StatusNotFound))
645+
// Unlike other detections, which inspect the schema, this one calls a real endpoint, so the header marks the request
646+
// as feature detection.
647+
resp, err := client.RequestWithContext(ctx, d.host, http.MethodGet, u.String(), nil,
648+
api.WithHeader("gh-feature-detection", "true"))
649+
if err != nil {
650+
if httpErr, ok := errors.AsType[api.HTTPError](err); ok &&
651+
(httpErr.StatusCode == http.StatusForbidden || httpErr.StatusCode == http.StatusNotFound) {
652+
return EventsFeatures{}, nil
653+
}
654+
return EventsFeatures{}, err
655+
}
656+
resp.Body.Close()
657+
658+
return EventsFeatures{Subscriptions: true}, nil
659+
}
660+
594661
func resolveEnterpriseVersion(httpClient *http.Client, host string) (*version.Version, error) {
595662
var metaResponse struct {
596663
InstalledVersion string `json:"installed_version"`

0 commit comments

Comments
 (0)