-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathCopilotJobProcessor.cs
More file actions
181 lines (160 loc) · 8.84 KB
/
Copy pathCopilotJobProcessor.cs
File metadata and controls
181 lines (160 loc) · 8.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using APIViewWeb.Helpers;
using APIViewWeb.Hubs;
using APIViewWeb.LeanModels;
using APIViewWeb.Managers.Interfaces;
using APIViewWeb.Models;
using APIViewWeb.Repositories;
using APIViewWeb.Services;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace APIViewWeb.HostedServices
{
public class CopilotJobProcessor : ICopilotJobProcessor
{
private readonly string _copilotEndpoint;
private readonly IHttpClientFactory _httpClientFactory;
private readonly IAPIRevisionsManager _apiRevisionsManager;
private readonly ICosmosCommentsRepository _commentsRepository;
private readonly ICopilotAuthenticationService _copilotAuthService;
private readonly IHubContext<SignalRHub> _signalRHubContext;
private readonly ILogger<CopilotJobProcessor> _logger;
private const string SummarySource = "summary";
public CopilotJobProcessor(
IConfiguration configuration,
IHttpClientFactory httpClientFactory,
IAPIRevisionsManager apiRevisionsManager,
ICosmosCommentsRepository commentsRepository,
ICopilotAuthenticationService copilotAuthService,
IHubContext<SignalRHub> signalRHubContext,
ILogger<CopilotJobProcessor> logger)
{
_copilotEndpoint = configuration["CopilotServiceEndpoint"];
_httpClientFactory = httpClientFactory;
_apiRevisionsManager = apiRevisionsManager;
_commentsRepository = commentsRepository;
_copilotAuthService = copilotAuthService;
_signalRHubContext = signalRHubContext;
_logger = logger;
}
public async Task ProcessJobAsync(AIReviewJobInfoModel jobInfo, CancellationToken cancellationToken = default)
{
_logger.LogInformation("Starting Copilot job processing for JobId: {JobId}, ReviewId: {ReviewId}, APIRevisionId: {APIRevisionId}",
jobInfo.JobId, jobInfo.APIRevision.ReviewId, jobInfo.APIRevision.Id);
try
{
cancellationToken.ThrowIfCancellationRequested();
var client = _httpClientFactory.CreateClient();
var pollUrl = $"{_copilotEndpoint}/api-review/{jobInfo.JobId}";
var poller = new Poller();
var result = await poller.PollAsync(
operation: async () =>
{
cancellationToken.ThrowIfCancellationRequested();
using var request = new HttpRequestMessage(HttpMethod.Get, pollUrl);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", await _copilotAuthService.GetAccessTokenAsync(cancellationToken));
HttpResponseMessage response = await client.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
string pollResponseString = await response.Content.ReadAsStringAsync(cancellationToken);
AIReviewJobPolledResponseModel pollResponse = JsonSerializer.Deserialize<AIReviewJobPolledResponseModel>(pollResponseString);
return pollResponse;
},
isComplete: response => (response.Status != "InProgress"),
initialInterval: 120, // Two minutes
maxInterval: 120,
cancellationToken: cancellationToken
);
if (result.Status == "Error")
{
_logger.LogError("Copilot job failed for JobId: {JobId}, ReviewId: {ReviewId}, APIRevisionId: {APIRevisionId}. Error: {ErrorDetails}",
jobInfo.JobId, jobInfo.APIRevision.ReviewId, jobInfo.APIRevision.Id, result.Details);
throw new Exception(result.Details);
}
List<AIReviewComment> validComments = result.Comments?
.Where(comment =>
jobInfo.CodeLines[comment.LineNo - 1].lineId != null || comment.Source == SummarySource)
.ToList() ?? new List<AIReviewComment>();
_logger.LogInformation("Processing {ValidCount} valid comments out of {TotalCount} for JobId: {JobId}, ReviewId: {ReviewId}",
validComments.Count, result.Comments?.Count ?? 0, jobInfo.JobId, jobInfo.APIRevision.ReviewId);
// Mark the revision as having been reviewed by Copilot
// when the job completes successfully, even if no valid
// comments were generated for this run.
if (string.Equals(result.Status, "Success", StringComparison.OrdinalIgnoreCase))
{
jobInfo.APIRevision.HasAutoGeneratedComments = true;
}
// Write back result as comments to APIView
foreach (var comment in validComments)
{
var codeLine = jobInfo.CodeLines[comment.LineNo - 1];
var commentModel = new CommentItemModel
{
CreatedOn = DateTime.UtcNow,
ReviewId = jobInfo.APIRevision.ReviewId,
APIRevisionId = jobInfo.APIRevision.Id,
ElementId = codeLine.lineId ?? (comment.Source == SummarySource ? CodeFileHelpers.FirstRowElementId : null),
IsGeneric = comment.IsGeneric,
CorrelationId = comment.CorrelationId,
GuidelineIds = comment.GuidelineIds ?? [],
MemoryIds = comment.MemoryIds ?? [],
Severity = CommentItemModel.ParseSeverity(comment.Severity),
ConfidenceScore = comment.ConfidenceScore,
CommentSource = CommentSource.AIGenerated,
ThreadId = Guid.NewGuid().ToString()
};
var commentText = new StringBuilder();
commentText.AppendLine(comment.Comment);
if (!String.IsNullOrEmpty(comment.Suggestion))
{
commentText.AppendLine();
commentText.AppendLine($"Suggestion : `{comment.Suggestion}`");
}
if (commentModel.GuidelineIds.Count > 0)
{
commentText.AppendLine();
commentText.AppendLine("**Guidelines**");
foreach (string guidelineId in commentModel.GuidelineIds)
{
commentText.AppendLine($"- https://azure.github.io/azure-sdk/{guidelineId}");
}
}
commentModel.ResolutionLocked = false;
commentModel.CreatedBy = ApiViewConstants.AzureSdkBotName;
commentModel.CommentText = commentText.ToString();
await _commentsRepository.UpsertCommentAsync(commentModel);
}
jobInfo.APIRevision.CopilotReviewInProgress = false;
await _apiRevisionsManager.UpdateAPIRevisionAsync(jobInfo.APIRevision);
await _signalRHubContext.Clients.All.SendAsync("ReceiveAIReviewUpdates", new AIReviewJobCompletedModel()
{
ReviewId = jobInfo.APIRevision.ReviewId,
APIRevisionId = jobInfo.APIRevision.Id,
Status = result.Status,
Details = result.Details,
CreatedBy = jobInfo.CreatedBy,
NoOfGeneratedComment = validComments.Count,
JobId = jobInfo.JobId
}, cancellationToken);
_logger.LogInformation("Completed Copilot job {JobId}: {Status}, generated {CommentsCount} comments for ReviewId: {ReviewId}, APIRevisionId: {APIRevisionId}",
jobInfo.JobId, result.Status, validComments.Count, jobInfo.APIRevision.ReviewId, jobInfo.APIRevision.Id);
}
catch (Exception e)
{
jobInfo.APIRevision.CopilotReviewInProgress = false;
await _apiRevisionsManager.UpdateAPIRevisionAsync(jobInfo.APIRevision);
_logger.LogError(e, "Error processing Copilot job {JobId}, ReviewId: {ReviewId}, APIRevisionId: {APIRevisionId}",
jobInfo.JobId, jobInfo.APIRevision.ReviewId, jobInfo.APIRevision.Id);
throw;
}
}
}
}