ListSessionsByResourceID retrieves sessions associated with the given resource type and ID.
(ctx context.Context, resourceType string, resourceID int64, limit int)
| 369 | |
| 370 | // ListSessionsByResourceID retrieves sessions associated with the given resource type and ID. |
| 371 | func (c *CAPIClient) ListSessionsByResourceID(ctx context.Context, resourceType string, resourceID int64, limit int) ([]*Session, error) { |
| 372 | if resourceType == "" || resourceID == 0 { |
| 373 | return nil, fmt.Errorf("missing resource type/ID") |
| 374 | } |
| 375 | |
| 376 | if limit == 0 { |
| 377 | return nil, nil |
| 378 | } |
| 379 | |
| 380 | u, err := safeurl.JoinPathWithHostPrefix(c.capiBaseURL, "agents", "resource", resourceType, strconv.FormatInt(resourceID, 10)) |
| 381 | if err != nil { |
| 382 | return nil, err |
| 383 | } |
| 384 | |
| 385 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), http.NoBody) |
| 386 | if err != nil { |
| 387 | return nil, err |
| 388 | } |
| 389 | |
| 390 | res, err := c.httpClient.Do(req) |
| 391 | if err != nil { |
| 392 | return nil, err |
| 393 | } |
| 394 | defer res.Body.Close() |
| 395 | if res.StatusCode != http.StatusOK { |
| 396 | return nil, fmt.Errorf("failed to list sessions: %s", res.Status) |
| 397 | } |
| 398 | |
| 399 | var response resource |
| 400 | if err := json.NewDecoder(res.Body).Decode(&response); err != nil { |
| 401 | return nil, fmt.Errorf("failed to decode sessions response: %w", err) |
| 402 | } |
| 403 | |
| 404 | sessions := make([]session, 0, len(response.Sessions)) |
| 405 | for _, s := range response.Sessions { |
| 406 | session := session{ |
| 407 | ID: s.SessionID, |
| 408 | Name: s.Name, |
| 409 | UserID: int64(response.UserID), |
| 410 | ResourceType: response.ResourceType, |
| 411 | ResourceID: response.ResourceID, |
| 412 | ResourceGlobalID: response.ResourceGlobalID, |
| 413 | State: s.SessionState, |
| 414 | } |
| 415 | if s.SessionLastUpdatedAt != 0 { |
| 416 | session.LastUpdatedAt = time.Unix(s.SessionLastUpdatedAt, 0).UTC() |
| 417 | } |
| 418 | sessions = append(sessions, session) |
| 419 | } |
| 420 | |
| 421 | result, err := c.hydrateSessionPullRequestsAndUsers(sessions) |
| 422 | if err != nil { |
| 423 | return nil, fmt.Errorf("failed to fetch session resources: %w", err) |
| 424 | } |
| 425 | return result, nil |
| 426 | } |
| 427 | |
| 428 | // hydrateSessionPullRequestsAndUsers hydrates pull request and user information in sessions |