forked from keithah/multi-provider-code-review
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub-review-state-adapter.ts
More file actions
274 lines (255 loc) · 8.43 KB
/
Copy pathgithub-review-state-adapter.ts
File metadata and controls
274 lines (255 loc) · 8.43 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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { createHash } from 'crypto';
import { GitHubClient } from '../../github/client';
import {
commandLedgerWatermark,
type LoadedLedger,
type ReviewLedger,
} from '../../github/ledger';
import {
ReviewThreadInventoryLoader,
type ReviewThreadInventory,
} from '../../github/review-thread-inventory';
import type { LifecycleTarget } from '../../types';
import type { ReviewRevisionGuardPort } from '../application';
import {
FindingSeverity,
LifecycleResolutionMarkerTrust,
LifecycleTargetDisposition,
type CurrentLifecycleInventory,
type ReviewProjectionScope,
} from '../../review-projection/domain';
import type { CurrentLifecycleInventoryPort } from '../../review-projection/application';
export type CanonicalReviewRevisionScope = {
readonly workspaceId: string;
readonly repositoryConnectionId: string;
readonly scmRepositoryIdentityId: string;
readonly pullRequestNumber: number;
};
export class GitHubReviewRevisionGuard implements ReviewRevisionGuardPort {
constructor(
private readonly client: GitHubClient,
private readonly scope: CanonicalReviewRevisionScope
) {}
async loadCurrentRevision() {
const before = await this.loadPointer();
const mergeBaseSha = await this.loadMergeBase(before);
const after = await this.loadPointer();
if (before.baseSha === after.baseSha && before.headSha === after.headSha) {
return this.toRevision(before, mergeBaseSha);
}
// Return the newest observed pointer so the application can cooperatively
// supersede. A later guard repeats the stable double-read before mutation.
return this.toRevision(after, await this.loadMergeBase(after));
}
private async loadPointer(): Promise<{
readonly baseSha: string;
readonly headSha: string;
}> {
const response = await this.client.octokit.rest.pulls.get({
owner: this.client.owner,
repo: this.client.repo,
pull_number: this.scope.pullRequestNumber,
});
return {
baseSha: requireCommitSha(response.data.base?.sha, 'base_sha'),
headSha: requireCommitSha(response.data.head?.sha, 'head_sha'),
};
}
private async loadMergeBase(pointer: {
readonly baseSha: string;
readonly headSha: string;
}): Promise<string> {
const response =
await this.client.octokit.rest.repos.compareCommitsWithBasehead({
owner: this.client.owner,
repo: this.client.repo,
basehead: `${pointer.baseSha}...${pointer.headSha}`,
});
return requireCommitSha(response.data.merge_base_commit?.sha, 'merge_base');
}
private toRevision(
pointer: { readonly baseSha: string; readonly headSha: string },
mergeBaseSha: string
) {
const facts = {
...this.scope,
baseSha: pointer.baseSha,
mergeBaseSha,
headSha: pointer.headSha,
};
return Object.freeze({
baseSha: facts.baseSha,
mergeBaseSha: facts.mergeBaseSha,
headSha: facts.headSha,
reviewRevisionHash: sha256(canonicalJson(facts)),
});
}
}
export class FreshGitHubLifecycleInventory implements CurrentLifecycleInventoryPort {
private readonly loader: ReviewThreadInventoryLoader;
constructor(
client: GitHubClient,
private readonly ledger: ReviewLedger
) {
this.loader = new ReviewThreadInventoryLoader(client);
}
async loadCurrent(query: {
readonly scope: ReviewProjectionScope;
}): Promise<CurrentLifecycleInventory> {
const [raw, ledger] = await Promise.all([
this.loader.load(query.scope.pullRequestNumber),
this.ledger.load(query.scope.pullRequestNumber),
]);
return mapFreshInventory(raw, query.scope.reviewedHeadSha, ledger);
}
async loadForPrompt(
pullRequestNumber: number,
expectedHeadSha: string
): Promise<{
readonly inventory: CurrentLifecycleInventory;
readonly promptTargets: readonly LifecycleTarget[];
}> {
const [raw, ledger] = await Promise.all([
this.loader.load(pullRequestNumber),
this.ledger.load(pullRequestNumber),
]);
const inventory = mapFreshInventory(raw, expectedHeadSha, ledger);
return Object.freeze({
inventory,
promptTargets: Object.freeze([
...raw.candidates,
...raw.manualAttention.map((record) => record.target),
]),
});
}
}
function mapFreshInventory(
raw: ReviewThreadInventory,
expectedHeadSha: string,
ledger: LoadedLedger
): CurrentLifecycleInventory {
if (raw.failed) {
throw new Error('review_action_v2_lifecycle_inventory_unavailable');
}
const loadedForHeadSha = requireCommitSha(
raw.headRefOid,
'lifecycle_head_sha'
);
if (loadedForHeadSha !== expectedHeadSha.toLowerCase()) {
throw new Error('review_action_v2_lifecycle_inventory_revision_mismatch');
}
const rawTargets = [
...raw.candidates.map((target) => ({ target, manual: false })),
...raw.manualAttention.map((record) => ({
target: record.target,
manual: true,
})),
].sort((left, right) =>
compareCodeUnits(left.target.targetId, right.target.targetId)
);
if (
new Set(rawTargets.map(({ target }) => target.targetId)).size !==
rawTargets.length
) {
throw new Error('review_action_v2_lifecycle_inventory_duplicate_target');
}
if (!ledger.valid) {
throw new Error('review_action_v2_command_ledger_unavailable');
}
const warnings = [...raw.warnings].sort();
const targets = rawTargets.map(({ target, manual }) => ({
targetId: target.targetId,
threadId: target.threadId,
trustedMarker: target.fingerprint,
title: target.title,
message: target.message,
severity: toProjectionSeverity(target.severity),
originalPath: target.originalPath,
...(target.currentPath ? { currentPath: target.currentPath } : {}),
...(target.originalLine !== undefined
? { originalLine: target.originalLine }
: {}),
...(target.currentLine !== undefined
? { currentLine: target.currentLine }
: {}),
parentCommentUpdatedAt: target.parentCommentUpdatedAt,
threadCommentCount: target.threadCommentCount,
disposition: target.reasonCodes?.includes('command_dismissed')
? LifecycleTargetDisposition.CommandSuppressed
: manual || target.hasHumanReply
? LifecycleTargetDisposition.HumanReply
: LifecycleTargetDisposition.Active,
viewerCanResolve: target.viewerCanResolve,
...(target.trustedResolutionMarker
? {
resolutionMarker: {
schemaVersion: target.trustedResolutionMarker.schemaVersion,
targetId: target.trustedResolutionMarker.targetId,
fingerprint: target.trustedResolutionMarker.fingerprint,
trust: LifecycleResolutionMarkerTrust.Trusted,
},
}
: {}),
}));
const commandWatermark = commandLedgerWatermark(ledger.payload);
const commandLedgerWatermarkValue = String(commandWatermark);
const lifecycleStateHash = sha256(
canonicalJson({
commandLedgerWatermark: commandLedgerWatermarkValue,
complete: true,
loadedForHeadSha,
targets,
warnings,
})
);
return Object.freeze({
inventoryVersion: 'review_lifecycle_inventory.v1',
loadedForHeadSha,
lifecycleStateHash,
commandLedgerWatermark: commandLedgerWatermarkValue,
complete: true,
warnings: Object.freeze(warnings),
targets: Object.freeze(targets),
});
}
function toProjectionSeverity(
severity: LifecycleTarget['severity']
): FindingSeverity | 'unknown' {
switch (severity) {
case 'critical':
return FindingSeverity.Critical;
case 'major':
return FindingSeverity.Major;
case 'minor':
return FindingSeverity.Minor;
default:
return 'unknown';
}
}
function requireCommitSha(value: unknown, field: string): string {
if (typeof value !== 'string' || !/^[a-f0-9]{40}$/i.test(value)) {
throw new Error(`review_action_v2_${field}_invalid`);
}
return value.toLowerCase();
}
function canonicalJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
if (value && typeof value === 'object') {
return `{${Object.keys(value as Record<string, unknown>)
.sort()
.map(
(key) =>
`${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`
)
.join(',')}}`;
}
return JSON.stringify(value);
}
function sha256(value: string): string {
return createHash('sha256').update(value).digest('hex');
}
function compareCodeUnits(left: string, right: string): number {
if (left < right) return -1;
if (left > right) return 1;
return 0;
}