| | | 1 | | using System.Net.Http.Json; |
| | | 2 | | using System.Text.Json.Serialization; |
| | | 3 | | |
| | | 4 | | namespace NexusLabs.Needlr.Copilot; |
| | | 5 | | |
| | | 6 | | /// <summary> |
| | | 7 | | /// Acquires and caches short-lived Copilot API tokens by exchanging a GitHub OAuth token |
| | | 8 | | /// (from <see cref="IGitHubOAuthTokenProvider"/>) via the internal GitHub API endpoint. |
| | | 9 | | /// Thread-safe: concurrent callers share a single refresh via <see cref="SemaphoreSlim"/>. |
| | | 10 | | /// </summary> |
| | | 11 | | internal sealed class CopilotTokenProvider : ICopilotTokenProvider, IDisposable |
| | | 12 | | { |
| | | 13 | | private readonly HttpClient _httpClient; |
| | | 14 | | private readonly CopilotChatClientOptions _options; |
| | | 15 | | private readonly IGitHubOAuthTokenProvider _oauthProvider; |
| | | 16 | | private readonly bool _ownsHttpClient; |
| | 15 | 17 | | private readonly SemaphoreSlim _refreshLock = new(1, 1); |
| | | 18 | | |
| | | 19 | | private string? _cachedToken; |
| | 15 | 20 | | private DateTimeOffset _expiresAt = DateTimeOffset.MinValue; |
| | | 21 | | |
| | | 22 | | public CopilotTokenProvider(CopilotChatClientOptions options, HttpClient? httpClient = null) |
| | 15 | 23 | | : this(new GitHubOAuthTokenProvider(options), options, httpClient) |
| | | 24 | | { |
| | 15 | 25 | | } |
| | | 26 | | |
| | 15 | 27 | | public CopilotTokenProvider( |
| | 15 | 28 | | IGitHubOAuthTokenProvider oauthProvider, |
| | 15 | 29 | | CopilotChatClientOptions options, |
| | 15 | 30 | | HttpClient? httpClient = null) |
| | | 31 | | { |
| | 15 | 32 | | _oauthProvider = oauthProvider ?? throw new ArgumentNullException(nameof(oauthProvider)); |
| | 15 | 33 | | _options = options ?? throw new ArgumentNullException(nameof(options)); |
| | 15 | 34 | | _ownsHttpClient = httpClient is null; |
| | 15 | 35 | | _httpClient = httpClient ?? new HttpClient(); |
| | 15 | 36 | | } |
| | | 37 | | |
| | | 38 | | public async Task<string> GetTokenAsync(CancellationToken cancellationToken = default) |
| | | 39 | | { |
| | 15 | 40 | | if (_cachedToken is not null && |
| | 15 | 41 | | DateTimeOffset.UtcNow.AddSeconds(_options.TokenRefreshBufferSeconds) < _expiresAt) |
| | | 42 | | { |
| | 1 | 43 | | return _cachedToken; |
| | | 44 | | } |
| | | 45 | | |
| | 14 | 46 | | await _refreshLock.WaitAsync(cancellationToken).ConfigureAwait(false); |
| | | 47 | | try |
| | | 48 | | { |
| | | 49 | | // Double-check after acquiring the lock |
| | 14 | 50 | | if (_cachedToken is not null && |
| | 14 | 51 | | DateTimeOffset.UtcNow.AddSeconds(_options.TokenRefreshBufferSeconds) < _expiresAt) |
| | | 52 | | { |
| | 0 | 53 | | return _cachedToken; |
| | | 54 | | } |
| | | 55 | | |
| | 14 | 56 | | var oauthToken = _oauthProvider.GetOAuthToken(); |
| | 14 | 57 | | var response = await ExchangeTokenAsync(oauthToken, cancellationToken).ConfigureAwait(false); |
| | | 58 | | |
| | 13 | 59 | | _cachedToken = response.Token; |
| | 13 | 60 | | _expiresAt = DateTimeOffset.FromUnixTimeSeconds(response.ExpiresAt); |
| | | 61 | | |
| | 13 | 62 | | return _cachedToken; |
| | | 63 | | } |
| | | 64 | | finally |
| | | 65 | | { |
| | 14 | 66 | | _refreshLock.Release(); |
| | | 67 | | } |
| | 14 | 68 | | } |
| | | 69 | | |
| | | 70 | | private async Task<CopilotTokenResponse> ExchangeTokenAsync( |
| | | 71 | | string oauthToken, CancellationToken cancellationToken) |
| | | 72 | | { |
| | 14 | 73 | | var url = $"{_options.GitHubApiBaseUrl.TrimEnd('/')}/copilot_internal/v2/token"; |
| | | 74 | | |
| | 14 | 75 | | using var request = new HttpRequestMessage(HttpMethod.Get, url); |
| | 14 | 76 | | request.Headers.Add("Authorization", $"token {oauthToken}"); |
| | 14 | 77 | | request.Headers.Add("Accept", "application/json"); |
| | 14 | 78 | | request.Headers.Add("User-Agent", _options.IntegrationId); |
| | | 79 | | |
| | 14 | 80 | | using var response = await _httpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); |
| | | 81 | | |
| | 14 | 82 | | if (!response.IsSuccessStatusCode) |
| | | 83 | | { |
| | 1 | 84 | | var body = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); |
| | 1 | 85 | | throw new HttpRequestException( |
| | 1 | 86 | | $"Copilot token exchange failed ({response.StatusCode}): {body}"); |
| | | 87 | | } |
| | | 88 | | |
| | 13 | 89 | | var tokenResponse = await response.Content |
| | 13 | 90 | | .ReadFromJsonAsync(CopilotJsonContext.Default.CopilotTokenResponse, cancellationToken) |
| | 13 | 91 | | .ConfigureAwait(false); |
| | | 92 | | |
| | 13 | 93 | | if (tokenResponse is null || string.IsNullOrWhiteSpace(tokenResponse.Token)) |
| | | 94 | | { |
| | 0 | 95 | | throw new InvalidOperationException("Copilot token exchange returned an empty token."); |
| | | 96 | | } |
| | | 97 | | |
| | 13 | 98 | | return tokenResponse; |
| | 13 | 99 | | } |
| | | 100 | | |
| | | 101 | | public void Dispose() |
| | | 102 | | { |
| | 15 | 103 | | _refreshLock.Dispose(); |
| | 15 | 104 | | if (_ownsHttpClient) |
| | | 105 | | { |
| | 1 | 106 | | _httpClient.Dispose(); |
| | | 107 | | } |
| | 15 | 108 | | } |
| | | 109 | | } |
| | | 110 | | |
| | | 111 | | internal sealed record CopilotTokenResponse |
| | | 112 | | { |
| | | 113 | | [JsonPropertyName("token")] |
| | | 114 | | public string Token { get; init; } = ""; |
| | | 115 | | |
| | | 116 | | [JsonPropertyName("expires_at")] |
| | | 117 | | public long ExpiresAt { get; init; } |
| | | 118 | | } |