|
| 1 | +package capi |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "encoding/base64" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "net/http" |
| 10 | + "slices" |
| 11 | + "strconv" |
| 12 | + "time" |
| 13 | + |
| 14 | + "github.com/cli/cli/v2/api" |
| 15 | + "github.com/vmihailenco/msgpack/v5" |
| 16 | +) |
| 17 | + |
| 18 | +// session is an in-flight agent task |
| 19 | +type session struct { |
| 20 | + ID string `json:"id"` |
| 21 | + Name string `json:"name"` |
| 22 | + UserID uint64 `json:"user_id"` |
| 23 | + AgentID int64 `json:"agent_id"` |
| 24 | + Logs string `json:"logs"` |
| 25 | + State string `json:"state"` |
| 26 | + OwnerID uint64 `json:"owner_id"` |
| 27 | + RepoID uint64 `json:"repo_id"` |
| 28 | + ResourceType string `json:"resource_type"` |
| 29 | + ResourceID int64 `json:"resource_id"` |
| 30 | + LastUpdatedAt time.Time `json:"last_updated_at,omitempty"` |
| 31 | + CreatedAt time.Time `json:"created_at,omitempty"` |
| 32 | + CompletedAt time.Time `json:"completed_at,omitempty"` |
| 33 | + EventURL string `json:"event_url"` |
| 34 | + EventType string `json:"event_type"` |
| 35 | +} |
| 36 | + |
| 37 | +// A shim of a full pull request because looking up by node ID |
| 38 | +// using the full api.PullRequest type fails on unions (actors) |
| 39 | +type sessionPullRequest struct { |
| 40 | + ID string |
| 41 | + FullDatabaseID string |
| 42 | + Number int |
| 43 | + Title string |
| 44 | + State string |
| 45 | + URL string |
| 46 | + Body string |
| 47 | + |
| 48 | + CreatedAt time.Time |
| 49 | + UpdatedAt time.Time |
| 50 | + ClosedAt *time.Time |
| 51 | + MergedAt *time.Time |
| 52 | + |
| 53 | + // Uncomment one of these to see error |
| 54 | + // Author api.Author |
| 55 | + // MergedBy *api.Author |
| 56 | + Repository *api.PRRepository |
| 57 | +} |
| 58 | + |
| 59 | +// Session is a hydrated in-flight agent task |
| 60 | +type Session struct { |
| 61 | + session |
| 62 | + PullRequest *api.PullRequest `json:"-"` |
| 63 | +} |
| 64 | + |
| 65 | +// ListSessionsForViewer lists all agent sessions for the |
| 66 | +// authenticated user up to limit. |
| 67 | +func (c *CAPIClient) ListSessionsForViewer(ctx context.Context, limit int) ([]*Session, error) { |
| 68 | + url := baseCAPIURL + "/agents/sessions" |
| 69 | + |
| 70 | + var sessions []session |
| 71 | + page := 1 |
| 72 | + perPage := 50 |
| 73 | + |
| 74 | + for { |
| 75 | + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, http.NoBody) |
| 76 | + if err != nil { |
| 77 | + return nil, err |
| 78 | + } |
| 79 | + |
| 80 | + q := req.URL.Query() |
| 81 | + q.Set("page_size", strconv.Itoa(perPage)) |
| 82 | + q.Set("page_number", strconv.Itoa(page)) |
| 83 | + req.URL.RawQuery = q.Encode() |
| 84 | + |
| 85 | + res, err := c.httpClient.Do(req) |
| 86 | + if err != nil { |
| 87 | + return nil, err |
| 88 | + } |
| 89 | + defer res.Body.Close() |
| 90 | + if res.StatusCode != http.StatusOK { |
| 91 | + return nil, fmt.Errorf("failed to list sessions: %s", res.Status) |
| 92 | + } |
| 93 | + var response struct { |
| 94 | + Sessions []session `json:"sessions"` |
| 95 | + } |
| 96 | + if err := json.NewDecoder(res.Body).Decode(&response); err != nil { |
| 97 | + return nil, fmt.Errorf("failed to decode sessions response: %w", err) |
| 98 | + } |
| 99 | + if len(response.Sessions) == 0 || len(sessions) >= limit { |
| 100 | + break |
| 101 | + } |
| 102 | + sessions = append(sessions, response.Sessions...) |
| 103 | + page++ |
| 104 | + } |
| 105 | + |
| 106 | + // Drop any above the limit |
| 107 | + if len(sessions) > limit { |
| 108 | + sessions = sessions[:limit] |
| 109 | + } |
| 110 | + |
| 111 | + // Hydrate the Sessions with pull request data. |
| 112 | + Sessions, err := c.hydrateSessionPullRequests(sessions) |
| 113 | + if err != nil { |
| 114 | + return nil, err |
| 115 | + } |
| 116 | + |
| 117 | + return Sessions, nil |
| 118 | +} |
| 119 | + |
| 120 | +// hydrateSessionPullRequests hydrates pull request information in sessions |
| 121 | +func (c *CAPIClient) hydrateSessionPullRequests(sessions []session) ([]*Session, error) { |
| 122 | + if len(sessions) == 0 { |
| 123 | + return nil, nil |
| 124 | + } |
| 125 | + |
| 126 | + prNodeIds := make([]string, 0, len(sessions)) |
| 127 | + |
| 128 | + for _, session := range sessions { |
| 129 | + prNodeID := generatePullRequestNodeID(int64(session.RepoID), session.ResourceID) |
| 130 | + if slices.Contains(prNodeIds, prNodeID) { |
| 131 | + continue |
| 132 | + } |
| 133 | + prNodeIds = append(prNodeIds, prNodeID) |
| 134 | + } |
| 135 | + |
| 136 | + apiClient := api.NewClientFromHTTP(c.httpClient) |
| 137 | + |
| 138 | + var resp struct { |
| 139 | + Nodes []struct { |
| 140 | + PullRequest sessionPullRequest `graphql:"... on PullRequest"` |
| 141 | + } `graphql:"nodes(ids: $ids)"` |
| 142 | + } |
| 143 | + |
| 144 | + host, _ := c.authCfg.DefaultHost() |
| 145 | + err := apiClient.Query(host, "FetchPRs", &resp, map[string]any{ |
| 146 | + "ids": prNodeIds, |
| 147 | + }) |
| 148 | + |
| 149 | + if err != nil { |
| 150 | + return nil, err |
| 151 | + } |
| 152 | + |
| 153 | + prs := make([]*api.PullRequest, 0, len(prNodeIds)) |
| 154 | + for _, node := range resp.Nodes { |
| 155 | + prs = append(prs, &api.PullRequest{ |
| 156 | + ID: node.PullRequest.ID, |
| 157 | + FullDatabaseID: node.PullRequest.FullDatabaseID, |
| 158 | + Number: node.PullRequest.Number, |
| 159 | + Title: node.PullRequest.Title, |
| 160 | + State: node.PullRequest.State, |
| 161 | + URL: node.PullRequest.URL, |
| 162 | + Body: node.PullRequest.Body, |
| 163 | + CreatedAt: node.PullRequest.CreatedAt, |
| 164 | + UpdatedAt: node.PullRequest.UpdatedAt, |
| 165 | + ClosedAt: node.PullRequest.ClosedAt, |
| 166 | + MergedAt: node.PullRequest.MergedAt, |
| 167 | + Repository: node.PullRequest.Repository, |
| 168 | + }) |
| 169 | + } |
| 170 | + |
| 171 | + newSessions := make([]*Session, 0, len(sessions)) |
| 172 | + // For each session, we need to attach the Pull Request |
| 173 | + for _, s := range sessions { |
| 174 | + // For each Pull Request, check if it matches the session |
| 175 | + for _, pr := range prs { |
| 176 | + if strconv.FormatInt(s.ResourceID, 10) == pr.FullDatabaseID { |
| 177 | + newSessions = append(newSessions, &Session{ |
| 178 | + session: s, |
| 179 | + PullRequest: pr, |
| 180 | + }) |
| 181 | + } |
| 182 | + } |
| 183 | + } |
| 184 | + |
| 185 | + return newSessions, nil |
| 186 | +} |
| 187 | + |
| 188 | +// generatePullRequestNodeID converts an int64 databaseID and repoID to a GraphQL Node ID format |
| 189 | +// with the "PR_" prefix for pull requests |
| 190 | +func generatePullRequestNodeID(repoID, pullRequestID int64) string { |
| 191 | + buf := bytes.Buffer{} |
| 192 | + parts := []int64{0, repoID, pullRequestID} |
| 193 | + |
| 194 | + encoder := msgpack.NewEncoder(&buf) |
| 195 | + encoder.UseCompactInts(true) |
| 196 | + |
| 197 | + // Encode the parts |
| 198 | + err := encoder.Encode(parts) |
| 199 | + if err != nil { |
| 200 | + panic(err) |
| 201 | + } |
| 202 | + |
| 203 | + // Use URL-safe Base64 encoding without padding |
| 204 | + encoded := base64.RawURLEncoding.EncodeToString(buf.Bytes()) |
| 205 | + |
| 206 | + // Return with the PR_ prefix |
| 207 | + return "PR_" + encoded |
| 208 | +} |
0 commit comments