plugin-git-manager 1.2.28 → 1.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +58 -40
- package/dist/client/941.1793e67472872992.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/locale/en-US.json +90 -1
- package/dist/locale/vi-VN.json +90 -1
- package/dist/locale/zh-CN.json +90 -1
- package/dist/node_modules/simple-git/package.json +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/actions/review-cutover.js +137 -0
- package/dist/server/actions/review.js +132 -43
- package/dist/server/actions/role-permissions.js +1 -0
- package/dist/server/ai-tools.js +8 -9
- package/dist/server/collections/gitCodeReviews.js +10 -0
- package/dist/server/collections/gitReviewCutover.js +44 -0
- package/dist/server/collections/gitReviewFlows.js +3 -0
- package/dist/server/collections/gitReviewInbox.js +51 -0
- package/dist/server/collections/gitReviewProjects.js +43 -0
- package/dist/server/collections/gitReviewRequests.js +56 -0
- package/dist/server/index.js +8 -2
- package/dist/server/plugin.js +51 -16
- package/dist/server/poller.js +54 -34
- package/dist/server/repository-access.js +23 -5
- package/dist/server/request-method-policy.js +2 -1
- package/dist/server/review-control-access.js +79 -0
- package/dist/server/services/legacy-post-service.js +412 -0
- package/dist/server/services/review-service.js +1451 -0
- package/dist/server/services/review-source.js +325 -0
- package/package.json +2 -2
- package/src/client/__tests__/CommitHistory.test.tsx +79 -0
- package/src/client/__tests__/ReviewHistory.test.tsx +126 -0
- package/src/client/__tests__/RunReviewButton.test.tsx +46 -35
- package/src/client/__tests__/workflowRoutes.test.ts +65 -0
- package/src/client/components/CommitHistory.tsx +61 -6
- package/src/client/components/ReviewFlows.tsx +90 -41
- package/src/client/components/ReviewHistory.tsx +245 -15
- package/src/client/components/RunReviewButton.tsx +12 -136
- package/src/client/workflowRoutes.ts +42 -0
- package/src/locale/en-US.json +90 -1
- package/src/locale/vi-VN.json +90 -1
- package/src/locale/zh-CN.json +90 -1
- package/src/server/__tests__/repository-access.test.ts +11 -3
- package/src/server/__tests__/review-service.integration.test.ts +1263 -0
- package/src/server/__tests__/review.test.ts +37 -98
- package/src/server/actions/review-cutover.ts +121 -0
- package/src/server/actions/review.ts +148 -38
- package/src/server/actions/role-permissions.ts +10 -0
- package/src/server/ai-tools.ts +23 -8
- package/src/server/collections/gitCodeReviews.ts +19 -0
- package/src/server/collections/gitReviewCutover.ts +23 -0
- package/src/server/collections/gitReviewFlows.ts +12 -0
- package/src/server/collections/gitReviewInbox.ts +30 -0
- package/src/server/collections/gitReviewProjects.ts +22 -0
- package/src/server/collections/gitReviewRequests.ts +35 -0
- package/src/server/index.ts +12 -0
- package/src/server/plugin.ts +43 -6
- package/src/server/poller.ts +54 -40
- package/src/server/repository-access.ts +32 -2
- package/src/server/request-method-policy.ts +1 -0
- package/src/server/review-control-access.ts +71 -0
- package/src/server/services/__tests__/review-source.test.ts +226 -0
- package/src/server/services/legacy-post-service.ts +550 -0
- package/src/server/services/review-service.ts +1899 -0
- package/src/server/services/review-source.ts +359 -0
- package/dist/client/900.a48beac7e2ebee7d.js +0 -10
- package/dist/client-v2/900.e6155002a9c97e7f.js +0 -10
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { execFileSync } from 'child_process';
|
|
11
|
+
import { createHash } from 'crypto';
|
|
12
|
+
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
|
|
13
|
+
import { tmpdir } from 'os';
|
|
14
|
+
import { join } from 'path';
|
|
15
|
+
import { Plugin } from '@nocobase/server';
|
|
16
|
+
import { getApp } from '@nocobase/plugin-workflow-test';
|
|
17
|
+
import type { MockServer } from '@nocobase/test';
|
|
18
|
+
import { vi } from 'vitest';
|
|
19
|
+
|
|
20
|
+
import { resolveBackgroundReviewRoles } from '../actions/review';
|
|
21
|
+
import PluginGitManagerServer from '../plugin';
|
|
22
|
+
import { resolveReviewProjectKey } from '../services/review-source';
|
|
23
|
+
import { GitReviewService } from '../services/review-service';
|
|
24
|
+
|
|
25
|
+
type RecordGetter = { get(name: string): unknown };
|
|
26
|
+
|
|
27
|
+
type ReviewFixture = {
|
|
28
|
+
repositoryId: number;
|
|
29
|
+
flowId: number;
|
|
30
|
+
workflowId: number;
|
|
31
|
+
headSha: string;
|
|
32
|
+
remoteUrl: string;
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
class SafeWorkflowTestPlugin extends Plugin {
|
|
36
|
+
enabled = true;
|
|
37
|
+
|
|
38
|
+
async assertSafeWorkflow(_workflowId: number | string, _postMode: string): Promise<void> {}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function numericId(record: RecordGetter): number {
|
|
42
|
+
const id = Number(record.get('id'));
|
|
43
|
+
if (!Number.isSafeInteger(id) || id < 1) throw new Error('Expected a positive database ID');
|
|
44
|
+
return id;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function runGit(repositoryPath: string, args: string[]): string {
|
|
48
|
+
return execFileSync('git', ['-C', repositoryPath, ...args], { encoding: 'utf8' }).trim();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function createLocalRepository(root: string, name: string, remoteUrl: string): ReviewFixture['headSha'] {
|
|
52
|
+
const repositoryPath = join(root, name);
|
|
53
|
+
mkdirSync(repositoryPath);
|
|
54
|
+
execFileSync('git', ['init', '--initial-branch=main', repositoryPath], { stdio: 'ignore' });
|
|
55
|
+
writeFileSync(join(repositoryPath, 'review-fixture.txt'), `${name}\n`);
|
|
56
|
+
execFileSync(
|
|
57
|
+
'git',
|
|
58
|
+
['-C', repositoryPath, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'add', '-A'],
|
|
59
|
+
{ stdio: 'ignore' },
|
|
60
|
+
);
|
|
61
|
+
execFileSync(
|
|
62
|
+
'git',
|
|
63
|
+
['-C', repositoryPath, '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', 'commit', '-m', 'fixture'],
|
|
64
|
+
{ stdio: 'ignore' },
|
|
65
|
+
);
|
|
66
|
+
execFileSync('git', ['-C', repositoryPath, 'remote', 'add', 'origin', remoteUrl], { stdio: 'ignore' });
|
|
67
|
+
return runGit(repositoryPath, ['rev-parse', 'HEAD']);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
type ReviewNote = { id: number; body: string; author: { id: number } };
|
|
71
|
+
|
|
72
|
+
function stubProviderFetch() {
|
|
73
|
+
const notes: ReviewNote[] = [];
|
|
74
|
+
const postedBodies: string[] = [];
|
|
75
|
+
const requestPaths: string[] = [];
|
|
76
|
+
let currentMrHead = 'b'.repeat(40);
|
|
77
|
+
let currentMrBase = 'a'.repeat(40);
|
|
78
|
+
let nextNoteListGate: { entered: () => void; wait: Promise<void> } | null = null;
|
|
79
|
+
let nextMergeRequestGate: {
|
|
80
|
+
entered: () => void;
|
|
81
|
+
wait: Promise<void>;
|
|
82
|
+
shouldHold?: () => Promise<boolean>;
|
|
83
|
+
} | null = null;
|
|
84
|
+
let noteListFailureAfter: { remaining: number; error: Error } | null = null;
|
|
85
|
+
let nextNotePostFailure: number | null = null;
|
|
86
|
+
const holdNextNoteList = () => {
|
|
87
|
+
let markEntered: (() => void) | undefined;
|
|
88
|
+
let release: (() => void) | undefined;
|
|
89
|
+
const entered = new Promise<void>((resolve) => {
|
|
90
|
+
markEntered = resolve;
|
|
91
|
+
});
|
|
92
|
+
const wait = new Promise<void>((resolve) => {
|
|
93
|
+
release = resolve;
|
|
94
|
+
});
|
|
95
|
+
nextNoteListGate = { entered: () => markEntered?.(), wait };
|
|
96
|
+
return { entered, release: () => release?.() };
|
|
97
|
+
};
|
|
98
|
+
const holdNextMergeRequest = (shouldHold?: () => Promise<boolean>) => {
|
|
99
|
+
let markEntered: (() => void) | undefined;
|
|
100
|
+
let release: (() => void) | undefined;
|
|
101
|
+
const entered = new Promise<void>((resolve) => {
|
|
102
|
+
markEntered = resolve;
|
|
103
|
+
});
|
|
104
|
+
const wait = new Promise<void>((resolve) => {
|
|
105
|
+
release = resolve;
|
|
106
|
+
});
|
|
107
|
+
nextMergeRequestGate = { entered: () => markEntered?.(), wait, shouldHold };
|
|
108
|
+
return { entered, release: () => release?.() };
|
|
109
|
+
};
|
|
110
|
+
const failNoteListAfter = (successfulReads: number, error = new Error('Injected note lookup failure')) => {
|
|
111
|
+
noteListFailureAfter = { remaining: successfulReads, error };
|
|
112
|
+
};
|
|
113
|
+
const failNextNotePost = (status = 503) => {
|
|
114
|
+
nextNotePostFailure = status;
|
|
115
|
+
};
|
|
116
|
+
const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
117
|
+
const url = new URL(String(input));
|
|
118
|
+
requestPaths.push(url.pathname);
|
|
119
|
+
const method = String(init?.method || 'GET').toUpperCase();
|
|
120
|
+
if (url.pathname.endsWith('/user')) {
|
|
121
|
+
return new Response(JSON.stringify({ id: 501 }), {
|
|
122
|
+
status: 200,
|
|
123
|
+
headers: { 'content-type': 'application/json' },
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
if (url.pathname.includes('/merge_requests/') && url.pathname.endsWith('/notes')) {
|
|
127
|
+
if (method === 'POST') {
|
|
128
|
+
const body = typeof init?.body === 'string' ? init.body : undefined;
|
|
129
|
+
const parsed = typeof body === 'string' ? (JSON.parse(body) as { body?: unknown }) : {};
|
|
130
|
+
if (typeof parsed.body !== 'string') throw new Error('Expected a review note body');
|
|
131
|
+
if (nextNotePostFailure != null) {
|
|
132
|
+
const status = nextNotePostFailure;
|
|
133
|
+
nextNotePostFailure = null;
|
|
134
|
+
return new Response('Injected note post failure', { status });
|
|
135
|
+
}
|
|
136
|
+
postedBodies.push(parsed.body);
|
|
137
|
+
const note = { id: 900 + postedBodies.length, body: parsed.body, author: { id: 501 } };
|
|
138
|
+
notes.push(note);
|
|
139
|
+
return new Response(JSON.stringify({ id: note.id }), {
|
|
140
|
+
status: 200,
|
|
141
|
+
headers: { 'content-type': 'application/json' },
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
if (noteListFailureAfter) {
|
|
145
|
+
if (noteListFailureAfter.remaining === 0) {
|
|
146
|
+
const { error } = noteListFailureAfter;
|
|
147
|
+
noteListFailureAfter = null;
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
noteListFailureAfter.remaining -= 1;
|
|
151
|
+
}
|
|
152
|
+
if (nextNoteListGate) {
|
|
153
|
+
const gate = nextNoteListGate;
|
|
154
|
+
nextNoteListGate = null;
|
|
155
|
+
gate.entered();
|
|
156
|
+
await gate.wait;
|
|
157
|
+
}
|
|
158
|
+
return new Response(JSON.stringify(notes), { status: 200, headers: { 'content-type': 'application/json' } });
|
|
159
|
+
}
|
|
160
|
+
const projectSegment = url.pathname.match(/\/projects\/([^/]+)/)?.[1];
|
|
161
|
+
if (!projectSegment) throw new Error(`Unexpected provider request: ${url.pathname}`);
|
|
162
|
+
const projectPath = decodeURIComponent(projectSegment).replace(/\.git$/, '');
|
|
163
|
+
const knownProjects = new Map([
|
|
164
|
+
['group/project', { id: 101, canonical: 'group/project' }],
|
|
165
|
+
['group/project-alias', { id: 101, canonical: 'group/project' }],
|
|
166
|
+
['group/other', { id: 202, canonical: 'group/other' }],
|
|
167
|
+
['group/legacy', { id: 303, canonical: 'group/legacy' }],
|
|
168
|
+
['group/legacy-alias', { id: 303, canonical: 'group/legacy' }],
|
|
169
|
+
]);
|
|
170
|
+
const knownProject = knownProjects.get(projectPath);
|
|
171
|
+
const projectId =
|
|
172
|
+
knownProject?.id ??
|
|
173
|
+
[...projectPath].reduce((id, character) => (id * 31 + character.charCodeAt(0)) % 2_000_000_000, 1_000);
|
|
174
|
+
const canonical = `https://gitlab.test/${knownProject?.canonical || projectPath}`;
|
|
175
|
+
if (url.pathname.includes('/merge_requests/')) {
|
|
176
|
+
if (nextMergeRequestGate && (!nextMergeRequestGate.shouldHold || (await nextMergeRequestGate.shouldHold()))) {
|
|
177
|
+
const gate = nextMergeRequestGate;
|
|
178
|
+
nextMergeRequestGate = null;
|
|
179
|
+
gate.entered();
|
|
180
|
+
await gate.wait;
|
|
181
|
+
}
|
|
182
|
+
return new Response(
|
|
183
|
+
JSON.stringify({
|
|
184
|
+
iid: 7,
|
|
185
|
+
sha: currentMrHead,
|
|
186
|
+
diff_refs: { head_sha: currentMrHead, base_sha: currentMrBase },
|
|
187
|
+
source_branch: 'main',
|
|
188
|
+
}),
|
|
189
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
return new Response(JSON.stringify({ id: projectId, web_url: canonical }), {
|
|
193
|
+
status: 200,
|
|
194
|
+
headers: { 'content-type': 'application/json' },
|
|
195
|
+
});
|
|
196
|
+
});
|
|
197
|
+
vi.stubGlobal('fetch', fetchMock as typeof fetch);
|
|
198
|
+
return {
|
|
199
|
+
fetchMock,
|
|
200
|
+
notes,
|
|
201
|
+
postedBodies,
|
|
202
|
+
requestPaths,
|
|
203
|
+
holdNextNoteList,
|
|
204
|
+
holdNextMergeRequest,
|
|
205
|
+
failNoteListAfter,
|
|
206
|
+
failNextNotePost,
|
|
207
|
+
setMrHead: (head: string) => {
|
|
208
|
+
currentMrHead = head;
|
|
209
|
+
},
|
|
210
|
+
setMrBase: (base: string) => {
|
|
211
|
+
currentMrBase = base;
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
describe('Git review service database integration', () => {
|
|
217
|
+
let app: MockServer;
|
|
218
|
+
let service: GitReviewService;
|
|
219
|
+
let fixtureRoot: string;
|
|
220
|
+
let actorId: number;
|
|
221
|
+
let actorRoles: string[];
|
|
222
|
+
let accountId: number;
|
|
223
|
+
let legacyPostService: PluginGitManagerServer['legacyPostService'];
|
|
224
|
+
let projectA: ReviewFixture;
|
|
225
|
+
let aliasA: ReviewFixture;
|
|
226
|
+
let projectB: ReviewFixture;
|
|
227
|
+
let legacyProject: ReviewFixture;
|
|
228
|
+
let legacyAlias: ReviewFixture;
|
|
229
|
+
const originalRepoRoot = process.env.GIT_REPOS_BASE_PATH;
|
|
230
|
+
|
|
231
|
+
beforeAll(async () => {
|
|
232
|
+
fixtureRoot = mkdtempSync(join(tmpdir(), 'git-review-service-'));
|
|
233
|
+
process.env.GIT_REPOS_BASE_PATH = fixtureRoot;
|
|
234
|
+
const remoteA = 'https://gitlab.test/group/project.git';
|
|
235
|
+
const remoteAlias = 'https://gitlab.test/group/project-alias.git';
|
|
236
|
+
const remoteB = 'https://gitlab.test/group/other.git';
|
|
237
|
+
const remoteLegacy = 'https://gitlab.test/group/legacy.git';
|
|
238
|
+
const remoteLegacyAlias = 'https://gitlab.test/group/legacy-alias.git';
|
|
239
|
+
const headA = createLocalRepository(fixtureRoot, 'repo-a', remoteA);
|
|
240
|
+
const headAlias = createLocalRepository(fixtureRoot, 'repo-alias', remoteAlias);
|
|
241
|
+
const headB = createLocalRepository(fixtureRoot, 'repo-b', remoteB);
|
|
242
|
+
const headLegacy = createLocalRepository(fixtureRoot, 'repo-legacy', remoteLegacy);
|
|
243
|
+
const headLegacyAlias = createLocalRepository(fixtureRoot, 'repo-legacy-alias', remoteLegacyAlias);
|
|
244
|
+
|
|
245
|
+
app = await getApp({
|
|
246
|
+
plugins: [
|
|
247
|
+
'error-handler',
|
|
248
|
+
'data-source-main',
|
|
249
|
+
[PluginGitManagerServer, { name: 'plugin-git-manager' }],
|
|
250
|
+
[SafeWorkflowTestPlugin, { name: 'workflow-git-review' }],
|
|
251
|
+
],
|
|
252
|
+
skipSupervisor: true,
|
|
253
|
+
});
|
|
254
|
+
const manager = app.pm.get('plugin-git-manager') as PluginGitManagerServer;
|
|
255
|
+
manager.reviewService.stop();
|
|
256
|
+
service = manager.reviewService;
|
|
257
|
+
legacyPostService = manager.legacyPostService;
|
|
258
|
+
|
|
259
|
+
const actor = await app.db.getRepository('users').findOne();
|
|
260
|
+
if (!actor) throw new Error('The disposable test database has no root actor');
|
|
261
|
+
actorId = numericId(actor);
|
|
262
|
+
actorRoles = await resolveBackgroundReviewRoles(app.db, actorId);
|
|
263
|
+
|
|
264
|
+
const account = await app.db.getRepository('gitAccounts').create({
|
|
265
|
+
values: {
|
|
266
|
+
name: 'Review test account',
|
|
267
|
+
provider: 'gitlab',
|
|
268
|
+
baseUrl: 'https://gitlab.test',
|
|
269
|
+
username: 'review-test',
|
|
270
|
+
pat: 'test-only-token',
|
|
271
|
+
},
|
|
272
|
+
});
|
|
273
|
+
accountId = numericId(account);
|
|
274
|
+
|
|
275
|
+
const createProject = async (
|
|
276
|
+
name: string,
|
|
277
|
+
localPath: string,
|
|
278
|
+
remoteUrl: string,
|
|
279
|
+
headSha: string,
|
|
280
|
+
workflowKey: string,
|
|
281
|
+
postMode: 'disabled' | 'auto' = 'disabled',
|
|
282
|
+
): Promise<ReviewFixture> => {
|
|
283
|
+
const repository = await app.db.getRepository('gitRepositories').create({
|
|
284
|
+
values: { name, repoUrl: remoteUrl, localPath, defaultBranch: 'main', gitAccountId: accountId },
|
|
285
|
+
});
|
|
286
|
+
const repositoryId = numericId(repository);
|
|
287
|
+
const workflow = await app.db.getRepository('workflows').create({
|
|
288
|
+
values: {
|
|
289
|
+
key: workflowKey,
|
|
290
|
+
title: `Review fixture ${name}`,
|
|
291
|
+
type: 'collection',
|
|
292
|
+
config: { collection: 'gitReviewFlows', mode: 1, condition: { id: { $eq: -1 } } },
|
|
293
|
+
enabled: true,
|
|
294
|
+
current: true,
|
|
295
|
+
sync: false,
|
|
296
|
+
options: { gitReview: { draft: false, workflowKey } },
|
|
297
|
+
},
|
|
298
|
+
});
|
|
299
|
+
const workflowId = numericId(workflow);
|
|
300
|
+
const flow = await app.db.getRepository('gitReviewFlows').create({
|
|
301
|
+
values: {
|
|
302
|
+
name: `Flow ${name}`,
|
|
303
|
+
repositoryId,
|
|
304
|
+
enabled: true,
|
|
305
|
+
triggerMode: 'both',
|
|
306
|
+
reviewOnNewCommits: false,
|
|
307
|
+
postMode,
|
|
308
|
+
workflowId,
|
|
309
|
+
workflowKey,
|
|
310
|
+
createdById: actorId,
|
|
311
|
+
},
|
|
312
|
+
});
|
|
313
|
+
const flowId = numericId(flow);
|
|
314
|
+
await app.db.getCollection('gitReviewFlows').model.update({ createdById: actorId }, { where: { id: flowId } });
|
|
315
|
+
return { repositoryId, flowId, workflowId, headSha, remoteUrl };
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
projectA = await createProject('Project A', 'repo-a', remoteA, headA, 'review-flow-a');
|
|
319
|
+
aliasA = await createProject('Project A alias', 'repo-alias', remoteAlias, headAlias, 'review-flow-alias');
|
|
320
|
+
projectB = await createProject('Project B', 'repo-b', remoteB, headB, 'review-flow-b');
|
|
321
|
+
legacyProject = await createProject(
|
|
322
|
+
'Legacy Project',
|
|
323
|
+
'repo-legacy',
|
|
324
|
+
remoteLegacy,
|
|
325
|
+
headLegacy,
|
|
326
|
+
'review-flow-legacy',
|
|
327
|
+
);
|
|
328
|
+
legacyAlias = await createProject(
|
|
329
|
+
'Legacy Project alias',
|
|
330
|
+
'repo-legacy-alias',
|
|
331
|
+
remoteLegacyAlias,
|
|
332
|
+
headLegacyAlias,
|
|
333
|
+
'review-flow-legacy-alias',
|
|
334
|
+
);
|
|
335
|
+
let cutover = await app.db.getRepository('gitReviewCutover').findOne({ filter: { key: 'global' } });
|
|
336
|
+
for (let attempt = 0; !cutover && attempt < 50; attempt += 1) {
|
|
337
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
338
|
+
cutover = await app.db.getRepository('gitReviewCutover').findOne({ filter: { key: 'global' } });
|
|
339
|
+
}
|
|
340
|
+
if (cutover) {
|
|
341
|
+
await app.db.getRepository('gitReviewCutover').update({
|
|
342
|
+
filterByTk: cutover.get('id'),
|
|
343
|
+
values: { state: 'awaiting_confirmation', confirmedBy: null, confirmedAt: null },
|
|
344
|
+
});
|
|
345
|
+
} else {
|
|
346
|
+
await app.db
|
|
347
|
+
.getRepository('gitReviewCutover')
|
|
348
|
+
.create({ values: { key: 'global', state: 'awaiting_confirmation' } });
|
|
349
|
+
}
|
|
350
|
+
}, 120_000);
|
|
351
|
+
|
|
352
|
+
async function createRetryScenarioProject(name: string): Promise<ReviewFixture> {
|
|
353
|
+
await app.db
|
|
354
|
+
.getCollection('gitReviewCutover')
|
|
355
|
+
.model.update({ state: 'ready', confirmedBy: actorId, confirmedAt: new Date() }, { where: { key: 'global' } });
|
|
356
|
+
const remoteUrl = `https://gitlab.test/group/${name}.git`;
|
|
357
|
+
const localPath = `repo-${name}`;
|
|
358
|
+
const headSha = createLocalRepository(fixtureRoot, localPath, remoteUrl);
|
|
359
|
+
const repository = await app.db.getRepository('gitRepositories').create({
|
|
360
|
+
values: {
|
|
361
|
+
name: `Retry scenario ${name}`,
|
|
362
|
+
repoUrl: remoteUrl,
|
|
363
|
+
localPath,
|
|
364
|
+
defaultBranch: 'main',
|
|
365
|
+
gitAccountId: accountId,
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
const repositoryId = numericId(repository);
|
|
369
|
+
const workflowKey = `review-flow-${name}`;
|
|
370
|
+
const workflow = await app.db.getRepository('workflows').create({
|
|
371
|
+
values: {
|
|
372
|
+
key: workflowKey,
|
|
373
|
+
title: `Review fixture ${name}`,
|
|
374
|
+
type: 'collection',
|
|
375
|
+
config: { collection: 'gitReviewFlows', mode: 1, condition: { id: { $eq: -1 } } },
|
|
376
|
+
enabled: true,
|
|
377
|
+
current: true,
|
|
378
|
+
sync: false,
|
|
379
|
+
options: { gitReview: { draft: false, workflowKey } },
|
|
380
|
+
},
|
|
381
|
+
});
|
|
382
|
+
const workflowId = numericId(workflow);
|
|
383
|
+
const flow = await app.db.getRepository('gitReviewFlows').create({
|
|
384
|
+
values: {
|
|
385
|
+
name: `Flow ${name}`,
|
|
386
|
+
repositoryId,
|
|
387
|
+
enabled: true,
|
|
388
|
+
triggerMode: 'both',
|
|
389
|
+
reviewOnNewCommits: false,
|
|
390
|
+
postMode: 'auto',
|
|
391
|
+
workflowId,
|
|
392
|
+
workflowKey,
|
|
393
|
+
createdById: actorId,
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
const flowId = numericId(flow);
|
|
397
|
+
await app.db.getCollection('gitReviewFlows').model.update({ createdById: actorId }, { where: { id: flowId } });
|
|
398
|
+
return { repositoryId, flowId, workflowId, headSha, remoteUrl };
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function createCompletedManagedReview(name: string, mrIid: number, markdown: string) {
|
|
402
|
+
const fixture = await createRetryScenarioProject(name);
|
|
403
|
+
const reviewId = await service.enqueue({
|
|
404
|
+
flowId: fixture.flowId,
|
|
405
|
+
repositoryId: fixture.repositoryId,
|
|
406
|
+
targetType: 'mr',
|
|
407
|
+
mrIid,
|
|
408
|
+
triggeredBy: 'manual',
|
|
409
|
+
userId: actorId,
|
|
410
|
+
actorRoles,
|
|
411
|
+
});
|
|
412
|
+
const inbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } });
|
|
413
|
+
const request =
|
|
414
|
+
inbox && (await app.db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: inbox.get('id') } }));
|
|
415
|
+
if (!inbox || !request) throw new Error('Expected an admitted managed review');
|
|
416
|
+
const markdownHash = createHash('sha256').update(markdown).digest('hex');
|
|
417
|
+
const execution = await app.db.getRepository('executions').create({
|
|
418
|
+
values: {
|
|
419
|
+
workflowId: request.get('workflowId'),
|
|
420
|
+
context: { data: { id: request.get('id'), workflowId: request.get('workflowId') } },
|
|
421
|
+
status: 1,
|
|
422
|
+
startedAt: new Date(),
|
|
423
|
+
endedAt: new Date(),
|
|
424
|
+
},
|
|
425
|
+
});
|
|
426
|
+
const executionId = numericId(execution);
|
|
427
|
+
const workflowPlugin = app.pm.get('workflow') as unknown as { snowflake: { getUniqueID(): bigint } };
|
|
428
|
+
for (const [key, title] of [
|
|
429
|
+
['gr_correctness', 'Correctness review'],
|
|
430
|
+
['gr_synthesis', 'Synthesize review'],
|
|
431
|
+
]) {
|
|
432
|
+
const node = await app.db.getRepository('flow_nodes').create({
|
|
433
|
+
values: {
|
|
434
|
+
workflowId: request.get('workflowId'),
|
|
435
|
+
key,
|
|
436
|
+
title,
|
|
437
|
+
type: 'git-review-llm',
|
|
438
|
+
config: { llmService: 'fixture-service', model: 'fixture-model' },
|
|
439
|
+
},
|
|
440
|
+
});
|
|
441
|
+
await app.db.getRepository('jobs').create({
|
|
442
|
+
values: {
|
|
443
|
+
id: workflowPlugin.snowflake.getUniqueID().toString(),
|
|
444
|
+
executionId,
|
|
445
|
+
nodeId: node.get('id'),
|
|
446
|
+
nodeKey: key,
|
|
447
|
+
status: 1,
|
|
448
|
+
result: { content: markdown },
|
|
449
|
+
startedAt: new Date(),
|
|
450
|
+
},
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
await app.db.getRepository('gitReviewRequests').update({
|
|
454
|
+
filterByTk: request.get('id'),
|
|
455
|
+
values: { executionId, aiSettled: true, resultFingerprint: markdownHash },
|
|
456
|
+
});
|
|
457
|
+
await app.db.getRepository('gitReviewInbox').update({
|
|
458
|
+
filterByTk: inbox.get('id'),
|
|
459
|
+
values: { state: 'completed' },
|
|
460
|
+
});
|
|
461
|
+
await app.db.getRepository('gitCodeReviews').update({
|
|
462
|
+
filterByTk: reviewId,
|
|
463
|
+
values: { status: 'completed', postStatus: 'post_unknown', reviewMarkdown: markdown },
|
|
464
|
+
});
|
|
465
|
+
await app.db
|
|
466
|
+
.getCollection('gitReviewProjects')
|
|
467
|
+
.model.update(
|
|
468
|
+
{ activeInboxId: null },
|
|
469
|
+
{ where: { projectKey: inbox.get('projectKey'), activeInboxId: inbox.get('id') } },
|
|
470
|
+
);
|
|
471
|
+
return {
|
|
472
|
+
fixture,
|
|
473
|
+
reviewId,
|
|
474
|
+
inbox,
|
|
475
|
+
request,
|
|
476
|
+
executionId,
|
|
477
|
+
markdownHash,
|
|
478
|
+
projectKey: String(inbox.get('projectKey')),
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async function createRunningManagedReview(name: string, mrIid: number) {
|
|
483
|
+
const fixture = await createRetryScenarioProject(name);
|
|
484
|
+
const reviewId = await service.enqueue({
|
|
485
|
+
flowId: fixture.flowId,
|
|
486
|
+
repositoryId: fixture.repositoryId,
|
|
487
|
+
targetType: 'mr',
|
|
488
|
+
mrIid,
|
|
489
|
+
triggeredBy: 'manual',
|
|
490
|
+
userId: actorId,
|
|
491
|
+
actorRoles,
|
|
492
|
+
});
|
|
493
|
+
const inbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } });
|
|
494
|
+
const request =
|
|
495
|
+
inbox && (await app.db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: inbox.get('id') } }));
|
|
496
|
+
if (!inbox || !request) throw new Error('Expected an admitted managed review');
|
|
497
|
+
const execution = await app.db.getRepository('executions').create({
|
|
498
|
+
values: {
|
|
499
|
+
workflowId: request.get('workflowId'),
|
|
500
|
+
context: { data: { id: request.get('id'), workflowId: request.get('workflowId') } },
|
|
501
|
+
status: 0,
|
|
502
|
+
startedAt: new Date(),
|
|
503
|
+
},
|
|
504
|
+
});
|
|
505
|
+
const executionId = numericId(execution);
|
|
506
|
+
await expect(service.claim(numericId(request), executionId)).resolves.toBe(true);
|
|
507
|
+
return { fixture, reviewId, inboxId: numericId(inbox), requestId: numericId(request), executionId };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
async function createLegacyPostScenario(
|
|
511
|
+
name: string,
|
|
512
|
+
mrIid: number,
|
|
513
|
+
markdown: string,
|
|
514
|
+
postStatus: 'posting' | 'post_unknown' | 'post_failed',
|
|
515
|
+
withPinnedSource = false,
|
|
516
|
+
) {
|
|
517
|
+
const fixture = await createRetryScenarioProject(name);
|
|
518
|
+
const repository = await app.db.getRepository('gitRepositories').findOne({ filterByTk: fixture.repositoryId });
|
|
519
|
+
if (!repository) throw new Error('Expected the historical review repository');
|
|
520
|
+
const projectKey = await resolveReviewProjectKey(app.db, repository);
|
|
521
|
+
await service.ensureReviewProject(projectKey);
|
|
522
|
+
const markdownHash = createHash('sha256').update(markdown).digest('hex');
|
|
523
|
+
const attemptId = `historical-${name}`;
|
|
524
|
+
const pinnedSource = {
|
|
525
|
+
projectKey,
|
|
526
|
+
repositoryId: fixture.repositoryId,
|
|
527
|
+
targetType: 'mr',
|
|
528
|
+
mrIid,
|
|
529
|
+
branch: null,
|
|
530
|
+
folderPath: null,
|
|
531
|
+
headSha: 'b'.repeat(40),
|
|
532
|
+
baseSha: 'a'.repeat(40),
|
|
533
|
+
};
|
|
534
|
+
const review = await app.db.getRepository('gitCodeReviews').create({
|
|
535
|
+
values: {
|
|
536
|
+
repositoryId: fixture.repositoryId,
|
|
537
|
+
flowId: fixture.flowId,
|
|
538
|
+
targetType: 'mr',
|
|
539
|
+
mrIid,
|
|
540
|
+
headSha: pinnedSource.headSha,
|
|
541
|
+
status: 'completed',
|
|
542
|
+
postStatus,
|
|
543
|
+
reviewMarkdown: markdown,
|
|
544
|
+
legacyPostFingerprint: markdownHash,
|
|
545
|
+
legacyPostClaim: attemptId,
|
|
546
|
+
legacyPostProjectKey: projectKey,
|
|
547
|
+
...(withPinnedSource
|
|
548
|
+
? {
|
|
549
|
+
legacyPostSource: pinnedSource,
|
|
550
|
+
legacyBaseProvenance: 'unverified_legacy',
|
|
551
|
+
legacyBaseAcknowledgedBy: String(actorId),
|
|
552
|
+
legacyBaseAcknowledgedAt: new Date(),
|
|
553
|
+
}
|
|
554
|
+
: {}),
|
|
555
|
+
createdById: actorId,
|
|
556
|
+
},
|
|
557
|
+
});
|
|
558
|
+
const reviewId = numericId(review);
|
|
559
|
+
const [reserved] = await app.db
|
|
560
|
+
.getCollection('gitReviewProjects')
|
|
561
|
+
.model.update(
|
|
562
|
+
{ legacyPostReviewId: reviewId },
|
|
563
|
+
{ where: { projectKey, activeInboxId: null, legacyPostReviewId: null } },
|
|
564
|
+
);
|
|
565
|
+
if (reserved !== 1) throw new Error('Expected to reserve the historical review project');
|
|
566
|
+
return { fixture, reviewId, projectKey, attemptId, markdownHash, pinnedSource };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
afterAll(async () => {
|
|
570
|
+
vi.unstubAllGlobals();
|
|
571
|
+
await app?.destroy();
|
|
572
|
+
if (originalRepoRoot === undefined) delete process.env.GIT_REPOS_BASE_PATH;
|
|
573
|
+
else process.env.GIT_REPOS_BASE_PATH = originalRepoRoot;
|
|
574
|
+
if (fixtureRoot) rmSync(fixtureRoot, { recursive: true, force: true });
|
|
575
|
+
});
|
|
576
|
+
|
|
577
|
+
it('dedupes poll events, serializes explicit reruns by canonical project, and admits separate projects concurrently', async () => {
|
|
578
|
+
const { fetchMock } = stubProviderFetch();
|
|
579
|
+
const enqueueManual = (fixture: ReviewFixture, targetType: 'commit' | 'mr', mrIid?: number) =>
|
|
580
|
+
service.enqueue({
|
|
581
|
+
flowId: fixture.flowId,
|
|
582
|
+
repositoryId: fixture.repositoryId,
|
|
583
|
+
targetType,
|
|
584
|
+
commitSha: targetType === 'commit' ? fixture.headSha : null,
|
|
585
|
+
mrIid: targetType === 'mr' ? mrIid : null,
|
|
586
|
+
triggeredBy: 'manual',
|
|
587
|
+
userId: actorId,
|
|
588
|
+
actorRoles,
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
const firstRun = await enqueueManual(projectA, 'commit');
|
|
592
|
+
const explicitRerun = await enqueueManual(projectA, 'commit');
|
|
593
|
+
const aliasRerun = await enqueueManual(aliasA, 'commit');
|
|
594
|
+
const pollFirst = await service.enqueue({
|
|
595
|
+
flowId: projectA.flowId,
|
|
596
|
+
repositoryId: projectA.repositoryId,
|
|
597
|
+
targetType: 'mr',
|
|
598
|
+
mrIid: 7,
|
|
599
|
+
triggeredBy: 'poll',
|
|
600
|
+
eventType: 'change_opened',
|
|
601
|
+
});
|
|
602
|
+
const pollDuplicate = await service.enqueue({
|
|
603
|
+
flowId: aliasA.flowId,
|
|
604
|
+
repositoryId: aliasA.repositoryId,
|
|
605
|
+
targetType: 'mr',
|
|
606
|
+
mrIid: 7,
|
|
607
|
+
triggeredBy: 'poll',
|
|
608
|
+
eventType: 'change_opened',
|
|
609
|
+
});
|
|
610
|
+
const differentProjectRun = await enqueueManual(projectB, 'commit');
|
|
611
|
+
|
|
612
|
+
expect(new Set([firstRun, explicitRerun, aliasRerun]).size).toBe(3);
|
|
613
|
+
expect(pollDuplicate).toBe(pollFirst);
|
|
614
|
+
expect(fetchMock).toHaveBeenCalled();
|
|
615
|
+
expect(await app.db.getRepository('gitReviewRequests').count()).toBe(0);
|
|
616
|
+
|
|
617
|
+
const queueDates = [
|
|
618
|
+
[firstRun, new Date('2020-01-01T00:00:00.000Z')],
|
|
619
|
+
[explicitRerun, new Date('2020-01-02T00:00:00.000Z')],
|
|
620
|
+
[aliasRerun, new Date('2020-01-03T00:00:00.000Z')],
|
|
621
|
+
[pollFirst, new Date('2020-01-04T00:00:00.000Z')],
|
|
622
|
+
[differentProjectRun, new Date('2020-01-01T00:00:00.000Z')],
|
|
623
|
+
] as const;
|
|
624
|
+
for (const [reviewId, queuedAt] of queueDates) {
|
|
625
|
+
const inbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } });
|
|
626
|
+
if (!inbox) throw new Error(`Missing inbox for review ${reviewId}`);
|
|
627
|
+
await app.db.getRepository('gitReviewInbox').update({
|
|
628
|
+
filterByTk: inbox.get('id'),
|
|
629
|
+
values: { queuedAt },
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
await service.confirmCutover(actorId);
|
|
634
|
+
await Promise.all([service.reconcile(), new GitReviewService(app).reconcile()]);
|
|
635
|
+
|
|
636
|
+
const reviews = await app.db.getRepository('gitCodeReviews').find({ sort: ['id'] });
|
|
637
|
+
expect(reviews).toHaveLength(5);
|
|
638
|
+
const firstInbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: firstRun } });
|
|
639
|
+
const secondInbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: explicitRerun } });
|
|
640
|
+
const aliasInbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: aliasRerun } });
|
|
641
|
+
const pollInbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: pollFirst } });
|
|
642
|
+
const otherInbox = await app.db
|
|
643
|
+
.getRepository('gitReviewInbox')
|
|
644
|
+
.findOne({ filter: { reviewId: differentProjectRun } });
|
|
645
|
+
expect(firstInbox?.get('state')).toBe('dispatched');
|
|
646
|
+
expect(secondInbox?.get('state')).toBe('queued');
|
|
647
|
+
expect(aliasInbox?.get('state')).toBe('queued');
|
|
648
|
+
expect(pollInbox?.get('state')).toBe('queued');
|
|
649
|
+
expect(otherInbox?.get('state')).toBe('dispatched');
|
|
650
|
+
|
|
651
|
+
const projectRows = await app.db.getRepository('gitReviewProjects').find({ sort: ['projectKey'] });
|
|
652
|
+
expect(projectRows).toHaveLength(2);
|
|
653
|
+
expect(projectRows.every((project) => project.get('activeInboxId') != null)).toBe(true);
|
|
654
|
+
|
|
655
|
+
await expect(app.eventQueue.publish('plugin-git-manager.review', { reviewId: firstRun })).rejects.toThrow(
|
|
656
|
+
'not subscribed',
|
|
657
|
+
);
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
it('keeps a failed or timed out execution quarantined until fenced administrative recovery', async () => {
|
|
661
|
+
const inbox = await app.db.getRepository('gitReviewInbox').findOne({
|
|
662
|
+
filter: { reviewId: (await app.db.getRepository('gitCodeReviews').findOne({ sort: ['id'] }))?.get('id') },
|
|
663
|
+
sort: ['id'],
|
|
664
|
+
});
|
|
665
|
+
if (!inbox) throw new Error('Expected the first project admission to retain its reservation');
|
|
666
|
+
const projectKey = String(inbox.get('projectKey'));
|
|
667
|
+
const active = await app.db.getRepository('gitReviewProjects').findOne({ filter: { projectKey } });
|
|
668
|
+
expect(active?.get('activeInboxId')).toBe(inbox.get('id'));
|
|
669
|
+
|
|
670
|
+
const request = await app.db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: inbox.get('id') } });
|
|
671
|
+
if (!request) throw new Error('Expected the dispatched review request');
|
|
672
|
+
const execution = await app.db.getRepository('executions').create({
|
|
673
|
+
values: {
|
|
674
|
+
workflowId: request.get('workflowId'),
|
|
675
|
+
context: { data: { id: request.get('id') } },
|
|
676
|
+
status: -1,
|
|
677
|
+
reason: 'timeout',
|
|
678
|
+
startedAt: new Date(),
|
|
679
|
+
endedAt: new Date(),
|
|
680
|
+
},
|
|
681
|
+
});
|
|
682
|
+
const executionId = numericId(execution);
|
|
683
|
+
await app.db.getRepository('gitReviewRequests').update({
|
|
684
|
+
filterByTk: request.get('id'),
|
|
685
|
+
values: { executionId },
|
|
686
|
+
});
|
|
687
|
+
await app.db.getRepository('gitReviewInbox').update({
|
|
688
|
+
filterByTk: inbox.get('id'),
|
|
689
|
+
values: { state: 'running' },
|
|
690
|
+
});
|
|
691
|
+
|
|
692
|
+
await service.onExecutionStatus(executionId, -1);
|
|
693
|
+
await service.reconcile();
|
|
694
|
+
|
|
695
|
+
const quarantined = await app.db.getRepository('gitReviewInbox').findOne({ filterByTk: inbox.get('id') });
|
|
696
|
+
const lockedProject = await app.db.getRepository('gitReviewProjects').findOne({ filter: { projectKey } });
|
|
697
|
+
expect(quarantined?.get('state')).toBe('quarantined');
|
|
698
|
+
expect(lockedProject?.get('activeInboxId')).toBe(inbox.get('id'));
|
|
699
|
+
|
|
700
|
+
await service.recover(numericId(request), executionId, actorId);
|
|
701
|
+
|
|
702
|
+
const recoveredRequest = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: request.get('id') });
|
|
703
|
+
const recoveredInbox = await app.db.getRepository('gitReviewInbox').findOne({ filterByTk: inbox.get('id') });
|
|
704
|
+
expect(recoveredRequest?.get('fenced')).toBe(true);
|
|
705
|
+
expect(recoveredInbox?.get('state')).toBe('recovered');
|
|
706
|
+
await expect(service.claim(numericId(request), executionId)).resolves.toBe(false);
|
|
707
|
+
|
|
708
|
+
const nextInbox = await app.db.getRepository('gitReviewInbox').findOne({
|
|
709
|
+
filter: { projectKey, state: 'dispatched' },
|
|
710
|
+
});
|
|
711
|
+
expect(nextInbox).toBeTruthy();
|
|
712
|
+
expect(nextInbox?.get('reviewId')).not.toBe(inbox.get('reviewId'));
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
it('drains legacy pending reviews while same-project legacy running rows block dispatch until stopped', async () => {
|
|
716
|
+
const reviews = app.db.getRepository('gitCodeReviews');
|
|
717
|
+
const pendingLegacy = await reviews.create({
|
|
718
|
+
values: {
|
|
719
|
+
repositoryId: legacyProject.repositoryId,
|
|
720
|
+
flowId: legacyProject.flowId,
|
|
721
|
+
targetType: 'commit',
|
|
722
|
+
commitSha: legacyProject.headSha,
|
|
723
|
+
headSha: legacyProject.headSha,
|
|
724
|
+
triggeredBy: 'poll',
|
|
725
|
+
status: 'pending',
|
|
726
|
+
postStatus: 'skipped',
|
|
727
|
+
createdById: actorId,
|
|
728
|
+
},
|
|
729
|
+
});
|
|
730
|
+
const runningLegacy = await reviews.create({
|
|
731
|
+
values: {
|
|
732
|
+
repositoryId: legacyAlias.repositoryId,
|
|
733
|
+
flowId: legacyAlias.flowId,
|
|
734
|
+
targetType: 'commit',
|
|
735
|
+
commitSha: legacyAlias.headSha,
|
|
736
|
+
headSha: legacyAlias.headSha,
|
|
737
|
+
triggeredBy: 'poll',
|
|
738
|
+
status: 'running',
|
|
739
|
+
postStatus: 'skipped',
|
|
740
|
+
startedAt: new Date(),
|
|
741
|
+
createdById: actorId,
|
|
742
|
+
},
|
|
743
|
+
});
|
|
744
|
+
const pendingId = numericId(pendingLegacy);
|
|
745
|
+
const runningId = numericId(runningLegacy);
|
|
746
|
+
const cutover = await app.db.getRepository('gitReviewCutover').findOne({ filter: { key: 'global' } });
|
|
747
|
+
if (!cutover) throw new Error('Expected the review cutover record');
|
|
748
|
+
await app.db.getRepository('gitReviewCutover').update({
|
|
749
|
+
filterByTk: cutover.get('id'),
|
|
750
|
+
values: { state: 'awaiting_confirmation', confirmedBy: null, confirmedAt: null },
|
|
751
|
+
});
|
|
752
|
+
|
|
753
|
+
const beforeConfirmation = await service.cutoverStatus();
|
|
754
|
+
expect(beforeConfirmation.state).toBe('awaiting_confirmation');
|
|
755
|
+
expect(
|
|
756
|
+
beforeConfirmation.legacyPendingReviews.some((item) => String(item.legacyReviewId) === String(pendingId)),
|
|
757
|
+
).toBe(true);
|
|
758
|
+
expect(
|
|
759
|
+
beforeConfirmation.legacyRunningReviews.some((item) => String(item.legacyReviewId) === String(runningId)),
|
|
760
|
+
).toBe(true);
|
|
761
|
+
|
|
762
|
+
await service.confirmCutover(actorId);
|
|
763
|
+
const migratedInbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: pendingId } });
|
|
764
|
+
const pendingProjectRow =
|
|
765
|
+
migratedInbox &&
|
|
766
|
+
(await app.db.getRepository('gitReviewProjects').findOne({
|
|
767
|
+
filter: { projectKey: migratedInbox.get('projectKey') },
|
|
768
|
+
}));
|
|
769
|
+
expect(migratedInbox?.get('legacyReviewId')).toBe(pendingId);
|
|
770
|
+
expect(migratedInbox?.get('state')).toBe('queued');
|
|
771
|
+
expect(pendingProjectRow?.get('activeInboxId')).toBeNull();
|
|
772
|
+
expect(
|
|
773
|
+
await app.db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: migratedInbox?.get('id') } }),
|
|
774
|
+
).toBeNull();
|
|
775
|
+
await expect(app.eventQueue.publish('plugin-git-manager.review', { reviewId: pendingId })).rejects.toThrow(
|
|
776
|
+
'not subscribed',
|
|
777
|
+
);
|
|
778
|
+
|
|
779
|
+
await service.recoverLegacy(runningId, actorId);
|
|
780
|
+
const recoveredLegacy = await reviews.findOne({ filterByTk: runningId });
|
|
781
|
+
const dispatchedInbox = await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: pendingId } });
|
|
782
|
+
const dispatchedRequest =
|
|
783
|
+
dispatchedInbox &&
|
|
784
|
+
(await app.db.getRepository('gitReviewRequests').findOne({
|
|
785
|
+
filter: { inboxId: dispatchedInbox.get('id') },
|
|
786
|
+
}));
|
|
787
|
+
const canonicalKeys = await app.db.getRepository('gitReviewProjects').find({
|
|
788
|
+
filter: { projectKey: migratedInbox?.get('projectKey') },
|
|
789
|
+
});
|
|
790
|
+
expect(recoveredLegacy?.get('status')).toBe('failed');
|
|
791
|
+
expect(dispatchedInbox?.get('state')).toBe('dispatched');
|
|
792
|
+
expect(dispatchedRequest).toBeTruthy();
|
|
793
|
+
expect(canonicalKeys).toHaveLength(1);
|
|
794
|
+
expect(canonicalKeys[0].get('activeInboxId')).toBe(dispatchedInbox?.get('id'));
|
|
795
|
+
});
|
|
796
|
+
|
|
797
|
+
it('does not enqueue a legacy row canceled before migration reaches enqueue', async () => {
|
|
798
|
+
stubProviderFetch();
|
|
799
|
+
await app.db.getCollection('gitReviewCutover').model.update({ state: 'ready' }, { where: { key: 'global' } });
|
|
800
|
+
const legacy = await app.db.getRepository('gitCodeReviews').create({
|
|
801
|
+
values: {
|
|
802
|
+
repositoryId: legacyProject.repositoryId,
|
|
803
|
+
flowId: legacyProject.flowId,
|
|
804
|
+
targetType: 'commit',
|
|
805
|
+
commitSha: legacyProject.headSha,
|
|
806
|
+
headSha: legacyProject.headSha,
|
|
807
|
+
triggeredBy: 'poll',
|
|
808
|
+
status: 'pending',
|
|
809
|
+
postStatus: 'skipped',
|
|
810
|
+
createdById: actorId,
|
|
811
|
+
},
|
|
812
|
+
});
|
|
813
|
+
const legacyReviewId = numericId(legacy);
|
|
814
|
+
let enteredMigration: (() => void) | undefined;
|
|
815
|
+
let releaseMigration: (() => void) | undefined;
|
|
816
|
+
const entered = new Promise<void>((resolve) => {
|
|
817
|
+
enteredMigration = resolve;
|
|
818
|
+
});
|
|
819
|
+
const gate = new Promise<void>((resolve) => {
|
|
820
|
+
releaseMigration = resolve;
|
|
821
|
+
});
|
|
822
|
+
const originalEnqueue = service.enqueue.bind(service);
|
|
823
|
+
let interceptedEnqueueCalls = 0;
|
|
824
|
+
const enqueueSpy = vi.spyOn(service, 'enqueue').mockImplementation(async (input) => {
|
|
825
|
+
if (String(input.legacyReviewId) === String(legacyReviewId)) {
|
|
826
|
+
interceptedEnqueueCalls += 1;
|
|
827
|
+
enteredMigration?.();
|
|
828
|
+
await gate;
|
|
829
|
+
}
|
|
830
|
+
return originalEnqueue(input);
|
|
831
|
+
});
|
|
832
|
+
const migration = service.reconcile();
|
|
833
|
+
try {
|
|
834
|
+
await entered;
|
|
835
|
+
await service.cancelLegacy(legacyReviewId, actorId);
|
|
836
|
+
} finally {
|
|
837
|
+
releaseMigration?.();
|
|
838
|
+
enqueueSpy.mockRestore();
|
|
839
|
+
}
|
|
840
|
+
await migration;
|
|
841
|
+
|
|
842
|
+
const canceled = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: legacyReviewId });
|
|
843
|
+
expect(canceled?.get('status')).toBe('failed');
|
|
844
|
+
expect(canceled?.get('metadata')).toMatchObject({ migrationCanceledBy: String(actorId) });
|
|
845
|
+
expect(await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: legacyReviewId } })).toBeNull();
|
|
846
|
+
expect(
|
|
847
|
+
await app.db.getRepository('gitReviewRequests').findOne({ filter: { reviewId: legacyReviewId } }),
|
|
848
|
+
).toBeNull();
|
|
849
|
+
expect(interceptedEnqueueCalls).toBe(1);
|
|
850
|
+
});
|
|
851
|
+
|
|
852
|
+
it.skipIf(process.env['DB_DIALECT'] === 'sqlite')(
|
|
853
|
+
'does not overwrite a legacy cancellation after migration reads the pending snapshot',
|
|
854
|
+
async () => {
|
|
855
|
+
expect(app.db.sequelize.getDialect()).toBe('postgres');
|
|
856
|
+
stubProviderFetch();
|
|
857
|
+
await app.db.getCollection('gitReviewCutover').model.update({ state: 'ready' }, { where: { key: 'global' } });
|
|
858
|
+
const legacy = await app.db.getRepository('gitCodeReviews').create({
|
|
859
|
+
values: {
|
|
860
|
+
repositoryId: legacyProject.repositoryId,
|
|
861
|
+
flowId: legacyProject.flowId,
|
|
862
|
+
targetType: 'commit',
|
|
863
|
+
commitSha: legacyProject.headSha,
|
|
864
|
+
headSha: legacyProject.headSha,
|
|
865
|
+
triggeredBy: 'poll',
|
|
866
|
+
status: 'pending',
|
|
867
|
+
postStatus: 'skipped',
|
|
868
|
+
createdById: actorId,
|
|
869
|
+
},
|
|
870
|
+
});
|
|
871
|
+
const legacyReviewId = numericId(legacy);
|
|
872
|
+
let cancelUpdateCompleted: (() => void) | undefined;
|
|
873
|
+
let releaseCancel: (() => void) | undefined;
|
|
874
|
+
const updateCompleted = new Promise<void>((resolve) => {
|
|
875
|
+
cancelUpdateCompleted = resolve;
|
|
876
|
+
});
|
|
877
|
+
const cancelGate = new Promise<void>((resolve) => {
|
|
878
|
+
releaseCancel = resolve;
|
|
879
|
+
});
|
|
880
|
+
const reviewModel = app.db.getCollection('gitCodeReviews').model;
|
|
881
|
+
const originalUpdate = reviewModel.update.bind(reviewModel);
|
|
882
|
+
const updateSpy = vi.spyOn(reviewModel, 'update').mockImplementation(async (values, options) => {
|
|
883
|
+
const changed = await originalUpdate(values, options);
|
|
884
|
+
const update = values as Record<string, unknown>;
|
|
885
|
+
const where = (options as { where?: Record<string, unknown> } | undefined)?.where;
|
|
886
|
+
if (
|
|
887
|
+
update.status === 'failed' &&
|
|
888
|
+
update.error === 'Legacy review canceled during workflow migration' &&
|
|
889
|
+
String(where?.id) === String(legacyReviewId)
|
|
890
|
+
) {
|
|
891
|
+
cancelUpdateCompleted?.();
|
|
892
|
+
await cancelGate;
|
|
893
|
+
}
|
|
894
|
+
return changed;
|
|
895
|
+
});
|
|
896
|
+
const cancel = service.cancelLegacy(legacyReviewId, actorId);
|
|
897
|
+
let migration: Promise<void> | undefined;
|
|
898
|
+
let cancelHeldRow = false;
|
|
899
|
+
try {
|
|
900
|
+
await updateCompleted;
|
|
901
|
+
migration = service.reconcile();
|
|
902
|
+
const deadline = Date.now() + 5_000;
|
|
903
|
+
while (Date.now() < deadline) {
|
|
904
|
+
const [rows] = await app.db.sequelize.query(
|
|
905
|
+
`SELECT pid FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND query ILIKE '%gitCodeReviews%'`,
|
|
906
|
+
);
|
|
907
|
+
if (Array.isArray(rows) && rows.length > 0) {
|
|
908
|
+
cancelHeldRow = true;
|
|
909
|
+
break;
|
|
910
|
+
}
|
|
911
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
912
|
+
}
|
|
913
|
+
} finally {
|
|
914
|
+
releaseCancel?.();
|
|
915
|
+
updateSpy.mockRestore();
|
|
916
|
+
await Promise.allSettled([cancel, migration || Promise.resolve()]);
|
|
917
|
+
}
|
|
918
|
+
expect(cancelHeldRow).toBe(true);
|
|
919
|
+
const canceled = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: legacyReviewId });
|
|
920
|
+
expect(canceled?.get('status')).toBe('failed');
|
|
921
|
+
expect(canceled?.get('metadata')).toMatchObject({ migrationCanceledBy: String(actorId) });
|
|
922
|
+
expect(await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: legacyReviewId } })).toBeNull();
|
|
923
|
+
expect(
|
|
924
|
+
await app.db.getRepository('gitReviewRequests').findOne({ filter: { reviewId: legacyReviewId } }),
|
|
925
|
+
).toBeNull();
|
|
926
|
+
},
|
|
927
|
+
);
|
|
928
|
+
|
|
929
|
+
it('serializes post retries and only records a verified outbound note', async () => {
|
|
930
|
+
const provider = stubProviderFetch();
|
|
931
|
+
const markdown = '## Review\n\nNo findings in the pinned diff.';
|
|
932
|
+
const { reviewId, inbox, request } = await createCompletedManagedReview('retry-serialized', 31, markdown);
|
|
933
|
+
const markdownHash = createHash('sha256').update(markdown).digest('hex');
|
|
934
|
+
|
|
935
|
+
const getOnly = await service.retryPost(reviewId, actorId, actorRoles, false);
|
|
936
|
+
expect(getOnly).toMatchObject({ status: 'unknown', canResend: true });
|
|
937
|
+
expect(provider.postedBodies).toHaveLength(0);
|
|
938
|
+
const released = await app.db
|
|
939
|
+
.getRepository('gitReviewProjects')
|
|
940
|
+
.findOne({ filter: { projectKey: inbox.get('projectKey') } });
|
|
941
|
+
expect(released?.get('activeInboxId')).toBeNull();
|
|
942
|
+
|
|
943
|
+
const gate = provider.holdNextNoteList();
|
|
944
|
+
const firstRetry = service.retryPost(reviewId, actorId, actorRoles, true);
|
|
945
|
+
await gate.entered;
|
|
946
|
+
const claimedRequest = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: request.get('id') });
|
|
947
|
+
const claimedProject = await app.db
|
|
948
|
+
.getRepository('gitReviewProjects')
|
|
949
|
+
.findOne({ filter: { projectKey: inbox.get('projectKey') } });
|
|
950
|
+
expect(typeof claimedRequest?.get('postClaim')).toBe('string');
|
|
951
|
+
expect(claimedProject?.get('activeInboxId')).toBe(inbox.get('id'));
|
|
952
|
+
await expect(service.retryPost(reviewId, actorId, actorRoles, true)).rejects.toMatchObject({ status: 409 });
|
|
953
|
+
gate.release();
|
|
954
|
+
|
|
955
|
+
await expect(firstRetry).resolves.toMatchObject({ status: 'posted', canResend: false });
|
|
956
|
+
const postedReview = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: reviewId });
|
|
957
|
+
const postedRequest = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: request.get('id') });
|
|
958
|
+
const finalProject = await app.db
|
|
959
|
+
.getRepository('gitReviewProjects')
|
|
960
|
+
.findOne({ filter: { projectKey: inbox.get('projectKey') } });
|
|
961
|
+
expect(postedReview?.get('postStatus')).toBe('posted');
|
|
962
|
+
expect(postedRequest?.get('postClaim')).toBeNull();
|
|
963
|
+
expect(finalProject?.get('activeInboxId')).toBeNull();
|
|
964
|
+
expect(provider.postedBodies).toEqual([`${markdown}\n\n<!-- git-review:${request.get('id')}:${markdownHash} -->`]);
|
|
965
|
+
});
|
|
966
|
+
|
|
967
|
+
it('keeps marker-only peer observations read-only and fences stale post reset tokens', async () => {
|
|
968
|
+
const provider = stubProviderFetch();
|
|
969
|
+
const markdown = '## Retry marker\n\nA complete immutable result.';
|
|
970
|
+
const { reviewId, inbox, request, markdownHash } = await createCompletedManagedReview('retry-marker', 32, markdown);
|
|
971
|
+
const projectKey = String(inbox.get('projectKey'));
|
|
972
|
+
await app.db
|
|
973
|
+
.getCollection('gitReviewProjects')
|
|
974
|
+
.model.update({ activeInboxId: inbox.get('id') }, { where: { projectKey, activeInboxId: null } });
|
|
975
|
+
const originalAttempt = 'previous-post-attempt';
|
|
976
|
+
await app.db.getRepository('gitReviewRequests').update({
|
|
977
|
+
filterByTk: request.get('id'),
|
|
978
|
+
values: { postClaim: originalAttempt, postClaimedAt: new Date() },
|
|
979
|
+
});
|
|
980
|
+
const marker = `<!-- git-review:${request.get('id')}:${markdownHash} -->`;
|
|
981
|
+
provider.notes.push({ id: 990, body: `${markdown}\n\n${marker}`, author: { id: 501 } });
|
|
982
|
+
|
|
983
|
+
const observed = await service.retryPost(reviewId, actorId, actorRoles, false);
|
|
984
|
+
expect(observed).toMatchObject({ status: 'observed', postedNoteId: '990', canResend: false });
|
|
985
|
+
const unchangedRequest = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: request.get('id') });
|
|
986
|
+
const heldProject = await app.db.getRepository('gitReviewProjects').findOne({ filter: { projectKey } });
|
|
987
|
+
expect(unchangedRequest?.get('postClaim')).toBe(originalAttempt);
|
|
988
|
+
expect(heldProject?.get('activeInboxId')).toBe(inbox.get('id'));
|
|
989
|
+
await expect(service.resetPostClaim(reviewId, actorId, 'wrong-attempt')).rejects.toMatchObject({ status: 409 });
|
|
990
|
+
await service.resetPostClaim(reviewId, actorId, originalAttempt);
|
|
991
|
+
const resetRequest = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: request.get('id') });
|
|
992
|
+
expect(resetRequest?.get('postClaim')).toBeNull();
|
|
993
|
+
const resetProject = await app.db.getRepository('gitReviewProjects').findOne({ filter: { projectKey } });
|
|
994
|
+
expect(resetProject?.get('activeInboxId')).toBeNull();
|
|
995
|
+
|
|
996
|
+
provider.setMrHead('c'.repeat(40));
|
|
997
|
+
const gate = provider.holdNextNoteList();
|
|
998
|
+
const ownerRetry = service.retryPost(reviewId, actorId, actorRoles, false);
|
|
999
|
+
await gate.entered;
|
|
1000
|
+
const newClaim = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: request.get('id') });
|
|
1001
|
+
const newAttempt = String(newClaim?.get('postClaim'));
|
|
1002
|
+
expect(newAttempt).not.toBe(originalAttempt);
|
|
1003
|
+
await expect(service.resetPostClaim(reviewId, actorId, originalAttempt)).rejects.toMatchObject({ status: 409 });
|
|
1004
|
+
const claimAfterStaleReset = await app.db
|
|
1005
|
+
.getRepository('gitReviewRequests')
|
|
1006
|
+
.findOne({ filterByTk: request.get('id') });
|
|
1007
|
+
expect(claimAfterStaleReset?.get('postClaim')).toBe(newAttempt);
|
|
1008
|
+
gate.release();
|
|
1009
|
+
|
|
1010
|
+
const pathsBeforeMarkerLookup = provider.requestPaths.length;
|
|
1011
|
+
await expect(ownerRetry).resolves.toMatchObject({ status: 'posted', postedNoteId: '990' });
|
|
1012
|
+
const retryPaths = provider.requestPaths.slice(pathsBeforeMarkerLookup);
|
|
1013
|
+
expect(retryPaths.some((path) => path.includes('/merge_requests/32') && !path.endsWith('/notes'))).toBe(false);
|
|
1014
|
+
expect(provider.postedBodies).toHaveLength(0);
|
|
1015
|
+
const postedReview = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: reviewId });
|
|
1016
|
+
expect(postedReview?.get('postStatus')).toBe('posted');
|
|
1017
|
+
});
|
|
1018
|
+
|
|
1019
|
+
it('blocks a new MR post after the base changes but still reconciles its exact existing marker', async () => {
|
|
1020
|
+
const provider = stubProviderFetch();
|
|
1021
|
+
const markdown = '## Base change check\n\nDo not publish against a changed base.';
|
|
1022
|
+
const { reviewId, inbox, request, markdownHash } = await createCompletedManagedReview(
|
|
1023
|
+
'retry-base-change',
|
|
1024
|
+
33,
|
|
1025
|
+
markdown,
|
|
1026
|
+
);
|
|
1027
|
+
|
|
1028
|
+
provider.setMrBase('c'.repeat(40));
|
|
1029
|
+
await expect(service.retryPost(reviewId, actorId, actorRoles, true)).rejects.toThrow();
|
|
1030
|
+
expect(provider.postedBodies).toHaveLength(0);
|
|
1031
|
+
expect(
|
|
1032
|
+
provider.fetchMock.mock.calls.some(([, init]) => String(init?.method || 'GET').toUpperCase() === 'POST'),
|
|
1033
|
+
).toBe(false);
|
|
1034
|
+
|
|
1035
|
+
const requestId = numericId(request);
|
|
1036
|
+
const marker = `<!-- git-review:${requestId}:${markdownHash} -->`;
|
|
1037
|
+
provider.notes.push({ id: 993, body: `${markdown}\n\n${marker}`, author: { id: 501 } });
|
|
1038
|
+
const beforeLookup = provider.requestPaths.length;
|
|
1039
|
+
const reconciled = await service.retryPost(reviewId, actorId, actorRoles, false);
|
|
1040
|
+
expect(['observed', 'posted']).toContain(reconciled.status);
|
|
1041
|
+
expect(reconciled).toMatchObject({ postedNoteId: '993', canResend: false });
|
|
1042
|
+
expect(
|
|
1043
|
+
provider.requestPaths
|
|
1044
|
+
.slice(beforeLookup)
|
|
1045
|
+
.some((path) => path.includes('/merge_requests/33') && !path.endsWith('/notes')),
|
|
1046
|
+
).toBe(false);
|
|
1047
|
+
expect(provider.postedBodies).toHaveLength(0);
|
|
1048
|
+
});
|
|
1049
|
+
|
|
1050
|
+
it.each(['posting', 'posted'] as const)(
|
|
1051
|
+
'does not rewind a %s publication when the same review result is saved again',
|
|
1052
|
+
async (postStatus) => {
|
|
1053
|
+
stubProviderFetch();
|
|
1054
|
+
const seeded = await createRunningManagedReview(`save-result-${postStatus}`, 34);
|
|
1055
|
+
const markdown = '## Immutable result\n\nThe workflow returned this exact review.';
|
|
1056
|
+
const hash = await service.saveResult(seeded.requestId, seeded.executionId, markdown);
|
|
1057
|
+
const claim = `active-${postStatus}-claim`;
|
|
1058
|
+
const noteId = postStatus === 'posted' ? 'existing-note-994' : null;
|
|
1059
|
+
await app.db.getRepository('gitReviewRequests').update({
|
|
1060
|
+
filterByTk: seeded.requestId,
|
|
1061
|
+
values: { postClaim: claim, postClaimedAt: new Date() },
|
|
1062
|
+
});
|
|
1063
|
+
await app.db.getRepository('gitCodeReviews').update({
|
|
1064
|
+
filterByTk: seeded.reviewId,
|
|
1065
|
+
values: { postStatus, postedNoteId: noteId },
|
|
1066
|
+
});
|
|
1067
|
+
|
|
1068
|
+
await expect(service.saveResult(seeded.requestId, seeded.executionId, markdown)).resolves.toBe(hash);
|
|
1069
|
+
|
|
1070
|
+
const review = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: seeded.reviewId });
|
|
1071
|
+
const request = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: seeded.requestId });
|
|
1072
|
+
expect(review?.get('postStatus')).toBe(postStatus);
|
|
1073
|
+
expect(review?.get('postedNoteId')).toBe(noteId);
|
|
1074
|
+
expect(request?.get('postClaim')).toBe(claim);
|
|
1075
|
+
},
|
|
1076
|
+
);
|
|
1077
|
+
|
|
1078
|
+
it.each(['post_failed', 'posting'] as const)(
|
|
1079
|
+
'recovers historical %s reviews by posting only the exact saved review after base acknowledgement',
|
|
1080
|
+
async (postStatus) => {
|
|
1081
|
+
const provider = stubProviderFetch();
|
|
1082
|
+
await app.db.getCollection('gitReviewCutover').model.update({ state: 'ready' }, { where: { key: 'global' } });
|
|
1083
|
+
const markdown = `## Historical ${postStatus}\n\nKeep the reviewed content byte-for-byte.`;
|
|
1084
|
+
const scenario = await createLegacyPostScenario(`historical-${postStatus}`, 41, markdown, postStatus);
|
|
1085
|
+
|
|
1086
|
+
const result = await legacyPostService.retry(
|
|
1087
|
+
scenario.reviewId,
|
|
1088
|
+
actorId,
|
|
1089
|
+
actorRoles,
|
|
1090
|
+
scenario.attemptId,
|
|
1091
|
+
'LEGACY_BASE_UNVERIFIED',
|
|
1092
|
+
);
|
|
1093
|
+
|
|
1094
|
+
const review = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: scenario.reviewId });
|
|
1095
|
+
const marker = `<!-- git-review:legacy:${scenario.reviewId}:${scenario.markdownHash} -->`;
|
|
1096
|
+
expect(result).toMatchObject({ status: 'posted', canRetry: false, baseAcknowledged: true });
|
|
1097
|
+
expect(provider.postedBodies).toEqual([`${markdown}\n\n${marker}`]);
|
|
1098
|
+
expect(provider.notes).toContainEqual({ id: 901, body: `${markdown}\n\n${marker}`, author: { id: 501 } });
|
|
1099
|
+
expect(review?.get('reviewMarkdown')).toBe(markdown);
|
|
1100
|
+
expect(review?.get('postStatus')).toBe('posted');
|
|
1101
|
+
expect(review?.get('legacyPostSource')).toMatchObject({
|
|
1102
|
+
projectKey: scenario.projectKey,
|
|
1103
|
+
repositoryId: scenario.fixture.repositoryId,
|
|
1104
|
+
mrIid: 41,
|
|
1105
|
+
headSha: 'b'.repeat(40),
|
|
1106
|
+
baseSha: 'a'.repeat(40),
|
|
1107
|
+
});
|
|
1108
|
+
expect(review?.get('legacyBaseProvenance')).toBe('unverified_legacy');
|
|
1109
|
+
expect(review?.get('legacyBaseAcknowledgedBy')).toBe(String(actorId));
|
|
1110
|
+
expect(
|
|
1111
|
+
await app.db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: scenario.reviewId } }),
|
|
1112
|
+
).toBeNull();
|
|
1113
|
+
},
|
|
1114
|
+
);
|
|
1115
|
+
|
|
1116
|
+
it('lets root release the canonical project hold after a marked legacy receipt and a failed second lookup', async () => {
|
|
1117
|
+
const provider = stubProviderFetch();
|
|
1118
|
+
await app.db.getCollection('gitReviewCutover').model.update({ state: 'ready' }, { where: { key: 'global' } });
|
|
1119
|
+
const markdown = '## Historical receipt\n\nThe marker proves the exact prior note.';
|
|
1120
|
+
const scenario = await createLegacyPostScenario('historical-marked-receipt', 42, markdown, 'post_unknown');
|
|
1121
|
+
const marker = `<!-- git-review:legacy:${scenario.reviewId}:${scenario.markdownHash} -->`;
|
|
1122
|
+
provider.notes.push({ id: 995, body: `${markdown}\n\n${marker}`, author: { id: 501 } });
|
|
1123
|
+
provider.failNoteListAfter(1);
|
|
1124
|
+
|
|
1125
|
+
await expect(
|
|
1126
|
+
legacyPostService.retry(scenario.reviewId, actorId, actorRoles, scenario.attemptId, undefined),
|
|
1127
|
+
).rejects.toThrow('Injected note lookup failure');
|
|
1128
|
+
|
|
1129
|
+
const held = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: scenario.reviewId });
|
|
1130
|
+
const heldProject = await app.db
|
|
1131
|
+
.getRepository('gitReviewProjects')
|
|
1132
|
+
.findOne({ filter: { projectKey: scenario.projectKey } });
|
|
1133
|
+
expect(held?.get('postStatus')).toBe('post_unknown');
|
|
1134
|
+
const currentAttempt = String(held?.get('legacyPostClaim'));
|
|
1135
|
+
expect(currentAttempt).not.toBe(scenario.attemptId);
|
|
1136
|
+
expect(heldProject?.get('legacyPostReviewId')).toBe(scenario.reviewId);
|
|
1137
|
+
expect(provider.postedBodies).toHaveLength(0);
|
|
1138
|
+
|
|
1139
|
+
await legacyPostService.releaseHold(scenario.reviewId, actorId, actorRoles, currentAttempt);
|
|
1140
|
+
|
|
1141
|
+
const released = await app.db
|
|
1142
|
+
.getRepository('gitReviewProjects')
|
|
1143
|
+
.findOne({ filter: { projectKey: scenario.projectKey } });
|
|
1144
|
+
const releasedReview = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: scenario.reviewId });
|
|
1145
|
+
expect(released?.get('legacyPostReviewId')).toBeNull();
|
|
1146
|
+
expect(releasedReview?.get('legacyHoldReleasedBy')).toBe(String(actorId));
|
|
1147
|
+
expect(releasedReview?.get('legacyPostClaim')).not.toBe(currentAttempt);
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
it('does not post managed review content after root resets its claim during the awaited head check', async () => {
|
|
1151
|
+
const provider = stubProviderFetch();
|
|
1152
|
+
const markdown = '## Stale managed claim\n\nNo post may start after reset.';
|
|
1153
|
+
const seeded = await createCompletedManagedReview('retry-reset-during-head', 43, markdown);
|
|
1154
|
+
const gate = provider.holdNextMergeRequest();
|
|
1155
|
+
const retry = service.retryPost(seeded.reviewId, actorId, actorRoles, true);
|
|
1156
|
+
try {
|
|
1157
|
+
await gate.entered;
|
|
1158
|
+
const claimed = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: seeded.request.get('id') });
|
|
1159
|
+
const attemptId = String(claimed?.get('postClaim'));
|
|
1160
|
+
expect(attemptId).not.toBe('null');
|
|
1161
|
+
await service.resetPostClaim(seeded.reviewId, actorId, attemptId);
|
|
1162
|
+
} finally {
|
|
1163
|
+
gate.release();
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
await expect(retry).rejects.toThrow();
|
|
1167
|
+
expect(
|
|
1168
|
+
provider.fetchMock.mock.calls.some(([, init]) => String(init?.method || 'GET').toUpperCase() === 'POST'),
|
|
1169
|
+
).toBe(false);
|
|
1170
|
+
const request = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: seeded.request.get('id') });
|
|
1171
|
+
const project = await app.db
|
|
1172
|
+
.getRepository('gitReviewProjects')
|
|
1173
|
+
.findOne({ filter: { projectKey: seeded.projectKey } });
|
|
1174
|
+
expect(request?.get('postClaim')).toBeNull();
|
|
1175
|
+
expect(project?.get('activeInboxId')).toBeNull();
|
|
1176
|
+
});
|
|
1177
|
+
|
|
1178
|
+
it('does not post a legacy review after root releases its hold during the awaited head check', async () => {
|
|
1179
|
+
const provider = stubProviderFetch();
|
|
1180
|
+
const scenario = await createLegacyPostScenario(
|
|
1181
|
+
'legacy-reset-during-head',
|
|
1182
|
+
44,
|
|
1183
|
+
'## Stale legacy claim\n\nNo post may start after release.',
|
|
1184
|
+
'post_failed',
|
|
1185
|
+
true,
|
|
1186
|
+
);
|
|
1187
|
+
const gate = provider.holdNextMergeRequest(async () => {
|
|
1188
|
+
const current = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: scenario.reviewId });
|
|
1189
|
+
return current?.get('postStatus') === 'posting' && String(current?.get('legacyPostClaim')) !== scenario.attemptId;
|
|
1190
|
+
});
|
|
1191
|
+
const manager = app.pm.get('plugin-git-manager') as PluginGitManagerServer;
|
|
1192
|
+
expect(manager.reviewService === service).toBe(true);
|
|
1193
|
+
expect((await service.cutoverStatus()).state).toBe('ready');
|
|
1194
|
+
const retry = legacyPostService.retry(scenario.reviewId, actorId, actorRoles, scenario.attemptId, undefined);
|
|
1195
|
+
let attemptId = scenario.attemptId;
|
|
1196
|
+
try {
|
|
1197
|
+
const reachedClaimedHeadCheck = await Promise.race([
|
|
1198
|
+
gate.entered.then(() => true),
|
|
1199
|
+
retry.then(
|
|
1200
|
+
() => false,
|
|
1201
|
+
(error: unknown) => {
|
|
1202
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1203
|
+
throw new Error(`Legacy retry failed before the gated head check: ${message}`);
|
|
1204
|
+
},
|
|
1205
|
+
),
|
|
1206
|
+
]);
|
|
1207
|
+
expect(reachedClaimedHeadCheck).toBe(true);
|
|
1208
|
+
const claimed = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: scenario.reviewId });
|
|
1209
|
+
attemptId = String(claimed?.get('legacyPostClaim'));
|
|
1210
|
+
expect(attemptId).not.toBe(scenario.attemptId);
|
|
1211
|
+
await legacyPostService.releaseHold(scenario.reviewId, actorId, actorRoles, attemptId);
|
|
1212
|
+
} finally {
|
|
1213
|
+
gate.release();
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
await expect(retry).rejects.toThrow();
|
|
1217
|
+
expect(
|
|
1218
|
+
provider.fetchMock.mock.calls.some(([, init]) => String(init?.method || 'GET').toUpperCase() === 'POST'),
|
|
1219
|
+
).toBe(false);
|
|
1220
|
+
const review = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: scenario.reviewId });
|
|
1221
|
+
const project = await app.db
|
|
1222
|
+
.getRepository('gitReviewProjects')
|
|
1223
|
+
.findOne({ filter: { projectKey: scenario.projectKey } });
|
|
1224
|
+
expect(review?.get('legacyPostClaim')).not.toBe(attemptId);
|
|
1225
|
+
expect(project?.get('legacyPostReviewId')).toBeNull();
|
|
1226
|
+
});
|
|
1227
|
+
|
|
1228
|
+
it('retains a managed publication claim when recording post_unknown fails after POST starts', async () => {
|
|
1229
|
+
const provider = stubProviderFetch();
|
|
1230
|
+
provider.failNextNotePost();
|
|
1231
|
+
const seeded = await createCompletedManagedReview(
|
|
1232
|
+
'retry-retain-claim-after-status-write-failure',
|
|
1233
|
+
45,
|
|
1234
|
+
'## Unknown outcome\n\nRetain the reservation when status persistence fails.',
|
|
1235
|
+
);
|
|
1236
|
+
const reviewModel = app.db.getCollection('gitCodeReviews').model;
|
|
1237
|
+
const originalUpdate = reviewModel.update.bind(reviewModel);
|
|
1238
|
+
const updateSpy = vi.spyOn(reviewModel, 'update').mockImplementation(async (values, options) => {
|
|
1239
|
+
const changedValues = values as unknown as Record<string, unknown>;
|
|
1240
|
+
if (changedValues.postStatus === 'post_unknown') throw new Error('Injected post_unknown write failure');
|
|
1241
|
+
return originalUpdate(values, options);
|
|
1242
|
+
});
|
|
1243
|
+
try {
|
|
1244
|
+
await expect(service.retryPost(seeded.reviewId, actorId, actorRoles, true)).rejects.toThrow(
|
|
1245
|
+
'Injected post_unknown write failure',
|
|
1246
|
+
);
|
|
1247
|
+
} finally {
|
|
1248
|
+
updateSpy.mockRestore();
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
expect(
|
|
1252
|
+
provider.fetchMock.mock.calls.some(([, init]) => String(init?.method || 'GET').toUpperCase() === 'POST'),
|
|
1253
|
+
).toBe(true);
|
|
1254
|
+
const review = await app.db.getRepository('gitCodeReviews').findOne({ filterByTk: seeded.reviewId });
|
|
1255
|
+
const request = await app.db.getRepository('gitReviewRequests').findOne({ filterByTk: seeded.request.get('id') });
|
|
1256
|
+
const project = await app.db
|
|
1257
|
+
.getRepository('gitReviewProjects')
|
|
1258
|
+
.findOne({ filter: { projectKey: seeded.projectKey } });
|
|
1259
|
+
expect(review?.get('postStatus')).toBe('retrying');
|
|
1260
|
+
expect(typeof request?.get('postClaim')).toBe('string');
|
|
1261
|
+
expect(project?.get('activeInboxId')).toBe(seeded.inbox.get('id'));
|
|
1262
|
+
});
|
|
1263
|
+
});
|