plugin-git-manager 1.2.27 → 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 +151 -108
- package/client-v2.d.ts +2 -2
- package/client-v2.js +1 -1
- package/client.d.ts +3 -3
- package/client.js +1 -1
- package/dist/client/{326.90c276058682b536.js → 313.d38fc1d40c4589b9.js} +1 -1
- package/dist/client/941.1793e67472872992.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/156.445366026c1cc9a8.js +10 -0
- package/dist/client-v2/{326.42b7b53651ffab3a.js → 313.3c867179c3a1e817.js} +1 -1
- package/dist/client-v2/434.19c7579c06b9077c.js +10 -0
- package/dist/client-v2/928.bba701b5a1ece58e.js +10 -0
- package/dist/client-v2/941.b0d55429cd053f32.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +9 -8
- package/dist/locale/en-US.json +396 -297
- package/dist/locale/vi-VN.json +384 -292
- package/dist/locale/zh-CN.json +150 -51
- package/dist/node_modules/simple-git/dist/cjs/index.js +25 -25
- package/dist/node_modules/simple-git/package.json +1 -1
- package/dist/node_modules/zod/index.cjs +1 -1
- package/dist/node_modules/zod/package.json +1 -1
- package/dist/server/actions/git-actions.js +90 -36
- package/dist/server/actions/gitlab-api.js +4 -2
- package/dist/server/actions/poller.js +5 -2
- package/dist/server/actions/review-cutover.js +137 -0
- package/dist/server/actions/review.js +150 -51
- 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 +57 -20
- package/dist/server/poller.js +95 -74
- package/dist/server/repository-access.js +23 -5
- package/dist/server/request-method-policy.js +76 -0
- package/dist/server/review-control-access.js +79 -0
- package/dist/server/services/legacy-post-service.js +412 -0
- package/dist/server/services/registry-content-service.js +4 -3
- package/dist/server/services/review-service.js +1451 -0
- package/dist/server/services/review-source.js +325 -0
- package/dist/server/utils/get-repo-account.js +3 -2
- package/dist/server/utils/url-security.js +24 -0
- package/package.json +61 -43
- package/server.d.ts +2 -2
- package/server.js +1 -1
- 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 +84 -0
- package/src/client/__tests__/workflowRoutes.test.ts +65 -0
- package/src/client/ai-context.tsx +114 -114
- package/src/client/components/AIEmployeeSelect.tsx +63 -63
- package/src/client/components/CommitHistory.tsx +429 -374
- package/src/client/components/FileExplorer.tsx +386 -386
- package/src/client/components/GitAccounts.tsx +179 -179
- package/src/client/components/GitManagerSettings.tsx +160 -160
- package/src/client/components/GitOperations.tsx +220 -220
- package/src/client/components/LLMModelSelect.tsx +63 -63
- package/src/client/components/LLMServiceSelect.tsx +58 -58
- package/src/client/components/MarkdownView.tsx +80 -80
- package/src/client/components/MergeRequests.tsx +790 -790
- package/src/client/components/PollingStatus.tsx +225 -225
- package/src/client/components/RepositoryConfig.tsx +335 -335
- package/src/client/components/RepositoryPermissions.tsx +123 -123
- package/src/client/components/ReviewFlows.tsx +352 -303
- package/src/client/components/ReviewHistory.tsx +796 -566
- package/src/client/components/RunReviewButton.tsx +57 -173
- package/src/client/context/GitManagerContext.tsx +92 -92
- package/src/client/index.tsx +91 -82
- package/src/client/locale.ts +9 -9
- package/src/client/promptTemplates.ts +31 -31
- package/src/client/workflowRoutes.ts +42 -0
- package/src/client-v2/ai-context.tsx +99 -0
- package/src/client-v2/components/SubtreeSplits.tsx +547 -547
- package/src/client-v2/index.tsx +1 -1
- package/src/client-v2/locale.ts +8 -8
- package/src/client-v2/plugin.tsx +67 -39
- package/src/index.ts +2 -2
- package/src/locale/en-US.json +396 -297
- package/src/locale/vi-VN.json +384 -292
- package/src/locale/zh-CN.json +150 -51
- package/src/server/__tests__/git-actions.test.ts +24 -24
- package/src/server/__tests__/git-security.test.ts +170 -0
- package/src/server/__tests__/plugin-url-security.test.ts +17 -17
- package/src/server/__tests__/poller-lifecycle.test.ts +71 -0
- package/src/server/__tests__/poller.test.ts +37 -37
- package/src/server/__tests__/repository-access.test.ts +760 -752
- package/src/server/__tests__/review-service.integration.test.ts +1263 -0
- package/src/server/__tests__/review.test.ts +76 -137
- package/src/server/__tests__/role-permissions.test.ts +147 -147
- package/src/server/__tests__/smoke.test.ts +139 -17
- package/src/server/__tests__/subtree.test.ts +85 -85
- package/src/server/actions/git-actions.ts +540 -480
- package/src/server/actions/gitlab-api.ts +422 -411
- package/src/server/actions/poller.ts +39 -27
- package/src/server/actions/review-cutover.ts +121 -0
- package/src/server/actions/review.ts +1498 -1369
- package/src/server/actions/role-permissions.ts +331 -321
- package/src/server/actions/subtree.ts +508 -508
- package/src/server/ai-tools.ts +334 -319
- package/src/server/collections/gitAccounts.ts +56 -56
- package/src/server/collections/gitCodeReviews.ts +218 -199
- package/src/server/collections/gitRepositories.ts +87 -87
- package/src/server/collections/gitReviewCutover.ts +23 -0
- package/src/server/collections/gitReviewFlows.ts +120 -108
- 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/collections/gitSubtreeConfigs.ts +38 -38
- package/src/server/collections/gitSubtreeRuns.ts +30 -30
- package/src/server/index.ts +14 -2
- package/src/server/migrations/20260508000000-add-auto-review-flow-id.ts +29 -29
- package/src/server/migrations/20260712000000-add-git-accounts.ts +198 -198
- package/src/server/migrations/20260730000000-migrate-legacy-repository-permissions.ts +81 -81
- package/src/server/plugin.ts +409 -361
- package/src/server/poller.ts +365 -352
- package/src/server/repository-access.ts +803 -773
- package/src/server/request-method-policy.ts +56 -0
- package/src/server/review-control-access.ts +71 -0
- package/src/server/services/__tests__/registry-content-service.test.ts +359 -345
- 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/registry-content-service.ts +495 -484
- package/src/server/services/review-service.ts +1899 -0
- package/src/server/services/review-source.ts +359 -0
- package/src/server/utils/__tests__/redact.test.ts +56 -56
- package/src/server/utils/__tests__/url-security.test.ts +85 -85
- package/src/server/utils/get-repo-account.ts +51 -41
- package/src/server/utils/gitlab-url.ts +38 -38
- package/src/server/utils/redact.ts +87 -87
- package/src/server/utils/url-security.ts +128 -95
- package/dist/client/900.acf7d1fa22f95e71.js +0 -10
- package/dist/client-v2/434.7a27051db18526c0.js +0 -10
- package/dist/client-v2/900.f32b9dc85249fc0a.js +0 -10
|
@@ -0,0 +1,1899 @@
|
|
|
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 { createHash, randomUUID } from 'crypto';
|
|
11
|
+
import type { Application } from '@nocobase/server';
|
|
12
|
+
import { Transaction } from 'sequelize';
|
|
13
|
+
import { branchMatches, pickFlowMatchingBranch, resolveBackgroundReviewRoles } from '../actions/review';
|
|
14
|
+
import { hasRepositoryAccess } from '../repository-access';
|
|
15
|
+
import {
|
|
16
|
+
assertCurrentMrHead,
|
|
17
|
+
findPublishedReview,
|
|
18
|
+
PinnedReviewSource,
|
|
19
|
+
publishPinnedReview,
|
|
20
|
+
readPinnedReviewSource,
|
|
21
|
+
resolveReviewProjectKey,
|
|
22
|
+
resolveReviewSource,
|
|
23
|
+
ReviewTarget,
|
|
24
|
+
} from './review-source';
|
|
25
|
+
|
|
26
|
+
type Id = number | string;
|
|
27
|
+
type Getter = { get(name: string): unknown };
|
|
28
|
+
|
|
29
|
+
export interface ReviewAdmission {
|
|
30
|
+
flowId?: number | null;
|
|
31
|
+
repositoryId: number;
|
|
32
|
+
targetType: ReviewTarget;
|
|
33
|
+
mrIid?: number | null;
|
|
34
|
+
commitSha?: string | null;
|
|
35
|
+
branch?: string | null;
|
|
36
|
+
folderPath?: string | null;
|
|
37
|
+
headSha?: string | null;
|
|
38
|
+
extraInstructions?: string;
|
|
39
|
+
triggeredBy?: 'manual' | 'poll';
|
|
40
|
+
eventType?: 'change_opened' | 'head_changed';
|
|
41
|
+
userId?: Id | null;
|
|
42
|
+
actorRoles?: string[];
|
|
43
|
+
legacyReviewId?: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
interface ReviewPayload {
|
|
47
|
+
source: PinnedReviewSource;
|
|
48
|
+
flowId: number;
|
|
49
|
+
workflowId: Id;
|
|
50
|
+
workflowKey: string;
|
|
51
|
+
eventType: 'manual' | 'change_opened' | 'head_changed';
|
|
52
|
+
userId: Id | null;
|
|
53
|
+
actorRoles: string[];
|
|
54
|
+
instructions: string;
|
|
55
|
+
postMode: 'manual' | 'auto' | 'disabled';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function value<T>(record: Getter, key: string): T {
|
|
59
|
+
return record.get(key) as T;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function fingerprint(markdown: string): string {
|
|
63
|
+
return createHash('sha256').update(markdown).digest('hex');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function reviewConflict(message: string): never {
|
|
67
|
+
const error = new Error(message) as Error & { status: number };
|
|
68
|
+
error.status = 409;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function legacyBlockReason(error: unknown): string {
|
|
73
|
+
const message = error instanceof Error ? error.message : '';
|
|
74
|
+
if (/Legacy review has no pinned source commit/.test(message)) return 'missing_pinned_head';
|
|
75
|
+
if (/Legacy branch review has no pinned base/.test(message)) return 'missing_pinned_base';
|
|
76
|
+
if (/head changed before review admission/.test(message)) return 'head_changed';
|
|
77
|
+
if (/actor has no unambiguous role|actor roles/.test(message)) return 'actor_role_ambiguous';
|
|
78
|
+
if (/authenticated actor|actor does not have repository access|unable to resolve roles/i.test(message))
|
|
79
|
+
return 'actor_unavailable';
|
|
80
|
+
if (/flow|workflow/i.test(message)) return 'flow_or_workflow_unavailable';
|
|
81
|
+
if (/Repository not found|project|origin/i.test(message)) return 'repository_unavailable';
|
|
82
|
+
return 'migration_failed';
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The reservation is deliberately not a lease: no clock expiry can prove an AI call stopped. */
|
|
86
|
+
export class GitReviewService {
|
|
87
|
+
readonly version = 1;
|
|
88
|
+
private timer: NodeJS.Timeout | null = null;
|
|
89
|
+
private reconciling = false;
|
|
90
|
+
|
|
91
|
+
constructor(private readonly app: Application) {}
|
|
92
|
+
|
|
93
|
+
async enqueue(input: ReviewAdmission): Promise<number> {
|
|
94
|
+
const db = this.app.db;
|
|
95
|
+
await this.cutoverStatus();
|
|
96
|
+
const repo = await db.getRepository('gitRepositories').findOne({ filterByTk: input.repositoryId });
|
|
97
|
+
if (!repo) throw new Error('Repository not found');
|
|
98
|
+
const source = await resolveReviewSource(db, repo, input);
|
|
99
|
+
const flows = db.getRepository('gitReviewFlows');
|
|
100
|
+
const candidates = input.flowId
|
|
101
|
+
? [await flows.findOne({ filterByTk: input.flowId })].filter(Boolean)
|
|
102
|
+
: await flows.find({
|
|
103
|
+
filter: { enabled: true, $or: [{ repositoryId: input.repositoryId }, { repositoryId: null }] },
|
|
104
|
+
sort: ['-repositoryId'],
|
|
105
|
+
});
|
|
106
|
+
const flow = input.flowId ? candidates[0] : pickFlowMatchingBranch(candidates, source.branch || undefined);
|
|
107
|
+
if (!flow || !value<boolean>(flow, 'enabled')) throw new Error('No enabled review flow found');
|
|
108
|
+
const flowRepoId = value<Id | null>(flow, 'repositoryId');
|
|
109
|
+
if (flowRepoId != null && String(flowRepoId) !== String(input.repositoryId))
|
|
110
|
+
throw new Error('Review flow does not belong to this repository');
|
|
111
|
+
if (source.branch && !branchMatches(flow, source.branch))
|
|
112
|
+
throw new Error('Source branch does not match review flow');
|
|
113
|
+
const eventType = input.triggeredBy === 'poll' ? input.eventType || 'change_opened' : 'manual';
|
|
114
|
+
const triggerMode = value<string>(flow, 'triggerMode');
|
|
115
|
+
if (eventType !== 'manual' && !['onMergeRequestCreated', 'both'].includes(triggerMode))
|
|
116
|
+
throw new Error('Flow does not permit automatic review');
|
|
117
|
+
if (eventType === 'head_changed' && !value<boolean>(flow, 'reviewOnNewCommits'))
|
|
118
|
+
throw new Error('Review of new commits is not enabled');
|
|
119
|
+
if (eventType === 'manual' && !['manual', 'both'].includes(triggerMode))
|
|
120
|
+
throw new Error('Flow does not permit manual review');
|
|
121
|
+
const workflowKey = value<string>(flow, 'workflowKey');
|
|
122
|
+
if (!workflowKey) throw new Error('Review flow has not been bound to a workflow');
|
|
123
|
+
const boundWorkflowId = value<Id | null>(flow, 'workflowId');
|
|
124
|
+
if (boundWorkflowId) {
|
|
125
|
+
const bound = await db.getRepository('workflows').findOne({ filterByTk: boundWorkflowId });
|
|
126
|
+
const options = bound ? value<{ gitReview?: { draft?: boolean } }>(bound, 'options') : null;
|
|
127
|
+
if (options?.gitReview?.draft === true) throw new Error('Review workflow setup is incomplete');
|
|
128
|
+
}
|
|
129
|
+
const workflow = await db
|
|
130
|
+
.getRepository('workflows')
|
|
131
|
+
.findOne({ filter: { key: workflowKey, current: true, enabled: true } });
|
|
132
|
+
if (!workflow) throw new Error('Review workflow is not enabled');
|
|
133
|
+
const workflowId = value<Id>(workflow, 'id');
|
|
134
|
+
const postMode = value<string>(flow, 'postMode');
|
|
135
|
+
const actorId = eventType === 'manual' ? input.userId ?? null : value<Id | null>(flow, 'createdById');
|
|
136
|
+
if (actorId == null) throw new Error('Review requires an authenticated actor');
|
|
137
|
+
const currentRoles = await resolveBackgroundReviewRoles(db, actorId);
|
|
138
|
+
const actorRoles = eventType === 'manual' ? input.actorRoles || [] : currentRoles;
|
|
139
|
+
if (!actorRoles.length || actorRoles.some((role) => !currentRoles.includes(role)))
|
|
140
|
+
throw new Error('Review actor roles are unavailable or changed');
|
|
141
|
+
if (
|
|
142
|
+
!(await hasRepositoryAccess({
|
|
143
|
+
acl: this.app.acl,
|
|
144
|
+
roles: actorRoles,
|
|
145
|
+
repositoryId: input.repositoryId,
|
|
146
|
+
action: 'triggerReview',
|
|
147
|
+
}))
|
|
148
|
+
)
|
|
149
|
+
throw new Error('Review actor does not have repository access');
|
|
150
|
+
const payload: ReviewPayload = {
|
|
151
|
+
source,
|
|
152
|
+
flowId: value<number>(flow, 'id'),
|
|
153
|
+
workflowId,
|
|
154
|
+
workflowKey,
|
|
155
|
+
eventType,
|
|
156
|
+
userId: actorId,
|
|
157
|
+
actorRoles,
|
|
158
|
+
instructions: [value<string | null>(flow, 'instructions'), input.extraInstructions].filter(Boolean).join('\n\n'),
|
|
159
|
+
postMode:
|
|
160
|
+
source.targetType !== 'mr' ? 'disabled' : postMode === 'auto' || postMode === 'disabled' ? postMode : 'manual',
|
|
161
|
+
};
|
|
162
|
+
await this.assertSafeWorkflow(workflowId, payload.postMode, undefined, input.repositoryId);
|
|
163
|
+
const eventKey =
|
|
164
|
+
eventType !== 'manual' && !input.legacyReviewId
|
|
165
|
+
? fingerprint(
|
|
166
|
+
`${source.projectKey}:mr:${source.mrIid}${
|
|
167
|
+
value<boolean>(flow, 'reviewOnNewCommits') ? `:${source.headSha}` : ''
|
|
168
|
+
}`,
|
|
169
|
+
)
|
|
170
|
+
: null;
|
|
171
|
+
const inboxRepo = db.getRepository('gitReviewInbox');
|
|
172
|
+
if (eventKey) {
|
|
173
|
+
const existing = await inboxRepo.findOne({ filter: { eventKey } });
|
|
174
|
+
if (existing) return value<number>(existing, 'reviewId');
|
|
175
|
+
}
|
|
176
|
+
if (input.legacyReviewId) {
|
|
177
|
+
const existing = await inboxRepo.findOne({ filter: { legacyReviewId: input.legacyReviewId } });
|
|
178
|
+
if (existing) return value<number>(existing, 'reviewId');
|
|
179
|
+
}
|
|
180
|
+
await this.ensureReviewProject(source.projectKey);
|
|
181
|
+
let reviewId: number;
|
|
182
|
+
try {
|
|
183
|
+
reviewId = await db.sequelize.transaction(async (transaction) => {
|
|
184
|
+
const reviews = db.getRepository('gitCodeReviews');
|
|
185
|
+
const values = {
|
|
186
|
+
flowId: payload.flowId,
|
|
187
|
+
repositoryId: input.repositoryId,
|
|
188
|
+
targetType: source.targetType,
|
|
189
|
+
mrIid: source.mrIid,
|
|
190
|
+
commitSha: source.targetType === 'commit' ? source.headSha : null,
|
|
191
|
+
branch: source.branch,
|
|
192
|
+
folderPath: source.folderPath,
|
|
193
|
+
headSha: source.headSha,
|
|
194
|
+
latestSha: source.headSha,
|
|
195
|
+
triggeredBy: eventType === 'manual' ? 'manual' : 'poll',
|
|
196
|
+
status: 'queued',
|
|
197
|
+
postStatus: source.targetType === 'mr' && payload.postMode !== 'disabled' ? 'pending_approval' : 'skipped',
|
|
198
|
+
createdById: payload.userId,
|
|
199
|
+
metadata: { workflowManaged: true },
|
|
200
|
+
startedAt: null,
|
|
201
|
+
finishedAt: null,
|
|
202
|
+
error: null,
|
|
203
|
+
};
|
|
204
|
+
let review: Getter;
|
|
205
|
+
if (input.legacyReviewId) {
|
|
206
|
+
const legacyReview = await db.getCollection('gitCodeReviews').model.findOne({
|
|
207
|
+
where: { id: input.legacyReviewId },
|
|
208
|
+
transaction,
|
|
209
|
+
lock: transaction.LOCK.UPDATE,
|
|
210
|
+
});
|
|
211
|
+
if (!legacyReview || value<string>(legacyReview, 'status') !== 'pending')
|
|
212
|
+
throw new Error('Legacy review is no longer pending');
|
|
213
|
+
review = legacyReview;
|
|
214
|
+
const [changed] = await db.getCollection('gitCodeReviews').model.update(values, {
|
|
215
|
+
where: { id: input.legacyReviewId, status: 'pending' },
|
|
216
|
+
transaction,
|
|
217
|
+
});
|
|
218
|
+
if (changed !== 1) throw new Error('Legacy review is no longer pending');
|
|
219
|
+
} else {
|
|
220
|
+
review = await reviews.create({ values, transaction });
|
|
221
|
+
}
|
|
222
|
+
const id = value<number>(review, 'id');
|
|
223
|
+
await inboxRepo.create({
|
|
224
|
+
values: {
|
|
225
|
+
projectKey: source.projectKey,
|
|
226
|
+
repositoryId: input.repositoryId,
|
|
227
|
+
reviewId: id,
|
|
228
|
+
legacyReviewId: input.legacyReviewId || null,
|
|
229
|
+
eventKey,
|
|
230
|
+
queuedAt: input.legacyReviewId ? value<Date>(review, 'createdAt') || new Date() : new Date(),
|
|
231
|
+
state: 'queued',
|
|
232
|
+
payload,
|
|
233
|
+
},
|
|
234
|
+
transaction,
|
|
235
|
+
});
|
|
236
|
+
return id;
|
|
237
|
+
});
|
|
238
|
+
} catch (error) {
|
|
239
|
+
if (eventKey) {
|
|
240
|
+
const existing = await inboxRepo.findOne({ filter: { eventKey } });
|
|
241
|
+
if (existing) return value<number>(existing, 'reviewId');
|
|
242
|
+
}
|
|
243
|
+
if (input.legacyReviewId) {
|
|
244
|
+
const existing = await inboxRepo.findOne({ filter: { legacyReviewId: input.legacyReviewId } });
|
|
245
|
+
if (existing) return value<number>(existing, 'reviewId');
|
|
246
|
+
}
|
|
247
|
+
throw error;
|
|
248
|
+
}
|
|
249
|
+
await this.reconcile().catch((error) => this.app.log?.error?.('Git review dispatch will be retried', error));
|
|
250
|
+
return reviewId;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
async ensureReviewProject(projectKey: string): Promise<void> {
|
|
254
|
+
const db = this.app.db;
|
|
255
|
+
const model = db.getCollection('gitReviewProjects').model;
|
|
256
|
+
for (let attempt = 0; ; attempt++) {
|
|
257
|
+
try {
|
|
258
|
+
await model.findOrCreate({ where: { projectKey }, defaults: { projectKey } });
|
|
259
|
+
return;
|
|
260
|
+
} catch (error) {
|
|
261
|
+
const sqliteError = error as { code?: string; original?: { code?: string }; parent?: { code?: string } };
|
|
262
|
+
const busy = [sqliteError.code, sqliteError.original?.code, sqliteError.parent?.code].includes('SQLITE_BUSY');
|
|
263
|
+
if (db.sequelize.getDialect() !== 'sqlite' || !busy || attempt >= 7) throw error;
|
|
264
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
private async assertSafeWorkflow(
|
|
270
|
+
workflowId: Id,
|
|
271
|
+
postMode: ReviewPayload['postMode'],
|
|
272
|
+
transaction?: Transaction,
|
|
273
|
+
repositoryId?: Id,
|
|
274
|
+
): Promise<void> {
|
|
275
|
+
const integration = (this.app.pm.get('plugin-workflow-git-review') ||
|
|
276
|
+
this.app.pm.get('workflow-git-review')) as unknown as
|
|
277
|
+
| {
|
|
278
|
+
enabled?: boolean;
|
|
279
|
+
assertSafeWorkflow?: (
|
|
280
|
+
id: Id,
|
|
281
|
+
mode: ReviewPayload['postMode'],
|
|
282
|
+
transaction?: Transaction,
|
|
283
|
+
repositoryId?: Id,
|
|
284
|
+
) => Promise<void>;
|
|
285
|
+
}
|
|
286
|
+
| undefined;
|
|
287
|
+
if (integration?.enabled !== true || !integration.assertSafeWorkflow)
|
|
288
|
+
throw new Error('Git review workflow integration is unavailable');
|
|
289
|
+
await integration.assertSafeWorkflow(workflowId, postMode, transaction, repositoryId);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private async legacyRows(): Promise<Getter[]> {
|
|
293
|
+
const db = this.app.db;
|
|
294
|
+
const candidates = await db
|
|
295
|
+
.getRepository('gitCodeReviews')
|
|
296
|
+
.find({ filter: { status: { $in: ['pending', 'running'] } }, sort: ['id'] });
|
|
297
|
+
const legacy: Getter[] = [];
|
|
298
|
+
for (const review of candidates) {
|
|
299
|
+
if (!(await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: value<Id>(review, 'id') } })))
|
|
300
|
+
legacy.push(review);
|
|
301
|
+
}
|
|
302
|
+
return legacy;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
async cutoverStatus(): Promise<{
|
|
306
|
+
state: string;
|
|
307
|
+
legacyPending: number;
|
|
308
|
+
legacyRunning: number;
|
|
309
|
+
legacyPendingReviews: Array<{ legacyReviewId: Id; repositoryId: Id; reason: string }>;
|
|
310
|
+
legacyRunningReviews: Array<{ legacyReviewId: Id }>;
|
|
311
|
+
legacyUncertain: number;
|
|
312
|
+
legacyUncertainReviews: Array<{ legacyReviewId: Id; repositoryId: Id }>;
|
|
313
|
+
quarantined: Array<{ requestId: Id; executionId: Id | null; reviewId: Id; reason: string }>;
|
|
314
|
+
orphaned: Array<{ inboxId: Id; reviewId: Id }>;
|
|
315
|
+
postUnknownReviews: Array<{ reviewId: Id; postStatus: string; hasClaim: boolean; attemptId: string | null }>;
|
|
316
|
+
legacyPublicationHolds: Array<{ reviewId: Id; repositoryId: Id | null; attemptId: string | null }>;
|
|
317
|
+
queuedBlockedReviews: Array<{ inboxId: Id; reviewId: Id; repositoryId: Id; reason: string }>;
|
|
318
|
+
}> {
|
|
319
|
+
const db = this.app.db;
|
|
320
|
+
const model = db.getCollection('gitReviewCutover').model;
|
|
321
|
+
const existingCount = await db.getRepository('gitCodeReviews').count();
|
|
322
|
+
let record = await model.findOne({ where: { key: 'global' } });
|
|
323
|
+
for (let attempt = 0; !record; attempt++) {
|
|
324
|
+
try {
|
|
325
|
+
[record] = await model.findOrCreate({
|
|
326
|
+
where: { key: 'global' },
|
|
327
|
+
defaults: { key: 'global', state: existingCount ? 'awaiting_confirmation' : 'ready' },
|
|
328
|
+
});
|
|
329
|
+
} catch (error) {
|
|
330
|
+
const sqliteError = error as { original?: { code?: string }; parent?: { code?: string } };
|
|
331
|
+
const busy = sqliteError.original?.code === 'SQLITE_BUSY' || sqliteError.parent?.code === 'SQLITE_BUSY';
|
|
332
|
+
if (!busy || attempt >= 4) throw error;
|
|
333
|
+
await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1)));
|
|
334
|
+
record = await model.findOne({ where: { key: 'global' } });
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const legacy = await this.legacyRows();
|
|
338
|
+
const failed = await db.getRepository('gitCodeReviews').find({ filter: { status: 'failed' }, sort: ['id'] });
|
|
339
|
+
const uncertain: Getter[] = [];
|
|
340
|
+
for (const review of failed) {
|
|
341
|
+
const metadata = value<Record<string, unknown> | null>(review, 'metadata');
|
|
342
|
+
if (!value<Date | null>(review, 'startedAt') || metadata?.workflowManaged) continue;
|
|
343
|
+
if (!(await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId: value<Id>(review, 'id') } })))
|
|
344
|
+
uncertain.push(review);
|
|
345
|
+
}
|
|
346
|
+
const activeRows = await db
|
|
347
|
+
.getRepository('gitReviewInbox')
|
|
348
|
+
.find({ filter: { state: { $in: ['dispatched', 'running', 'quarantined'] } }, sort: ['id'] });
|
|
349
|
+
const quarantined: Array<{ requestId: Id; executionId: Id | null; reviewId: Id; reason: string }> = [];
|
|
350
|
+
const orphaned: Array<{ inboxId: Id; reviewId: Id }> = [];
|
|
351
|
+
const postUnknownReviews: Array<{ reviewId: Id; postStatus: string; hasClaim: boolean; attemptId: string | null }> =
|
|
352
|
+
[];
|
|
353
|
+
const legacyPublicationHolds: Array<{ reviewId: Id; repositoryId: Id | null; attemptId: string | null }> = [];
|
|
354
|
+
const legacyProjects = await db.getRepository('gitReviewProjects').find({
|
|
355
|
+
filter: { legacyPostReviewId: { $ne: null } },
|
|
356
|
+
sort: ['id'],
|
|
357
|
+
limit: 100,
|
|
358
|
+
});
|
|
359
|
+
for (const project of legacyProjects) {
|
|
360
|
+
const reviewId = value<Id>(project, 'legacyPostReviewId');
|
|
361
|
+
const heldReview = await db.getRepository('gitCodeReviews').findOne({ filterByTk: reviewId });
|
|
362
|
+
legacyPublicationHolds.push({
|
|
363
|
+
reviewId,
|
|
364
|
+
repositoryId: heldReview ? value<Id>(heldReview, 'repositoryId') : null,
|
|
365
|
+
attemptId: heldReview ? value<string | null>(heldReview, 'legacyPostClaim') ?? null : null,
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
const queuedBlocked = await db
|
|
369
|
+
.getRepository('gitReviewInbox')
|
|
370
|
+
.find({ filter: { state: 'queued', blockedReason: { $ne: null } }, sort: ['queuedAt', 'id'], limit: 100 });
|
|
371
|
+
const unresolved = await db
|
|
372
|
+
.getRepository('gitCodeReviews')
|
|
373
|
+
.find({ filter: { postStatus: { $in: ['posting', 'post_unknown', 'post_failed', 'retrying'] } }, sort: ['id'] });
|
|
374
|
+
for (const review of unresolved) {
|
|
375
|
+
if (
|
|
376
|
+
value<{ workflowManaged?: boolean } | null>(review, 'metadata')?.workflowManaged &&
|
|
377
|
+
postUnknownReviews.length < 100
|
|
378
|
+
) {
|
|
379
|
+
const inbox = await db
|
|
380
|
+
.getRepository('gitReviewInbox')
|
|
381
|
+
.findOne({ filter: { reviewId: value<Id>(review, 'id') } });
|
|
382
|
+
const request =
|
|
383
|
+
inbox &&
|
|
384
|
+
(await db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: value<Id>(inbox, 'id') } }));
|
|
385
|
+
const attemptId = request ? value<string | null>(request, 'postClaim') ?? null : null;
|
|
386
|
+
postUnknownReviews.push({
|
|
387
|
+
reviewId: value<Id>(review, 'id'),
|
|
388
|
+
postStatus: value<string>(review, 'postStatus'),
|
|
389
|
+
hasClaim: attemptId != null,
|
|
390
|
+
attemptId,
|
|
391
|
+
});
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
for (const inbox of activeRows) {
|
|
395
|
+
const request = await db
|
|
396
|
+
.getRepository('gitReviewRequests')
|
|
397
|
+
.findOne({ filter: { inboxId: value<Id>(inbox, 'id') } });
|
|
398
|
+
if (!request) {
|
|
399
|
+
if (orphaned.length < 100)
|
|
400
|
+
orphaned.push({ inboxId: value<Id>(inbox, 'id'), reviewId: value<Id>(inbox, 'reviewId') });
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
const executionId = value<Id | null>(request, 'executionId');
|
|
404
|
+
const execution =
|
|
405
|
+
executionId == null || !db.getCollection('executions')
|
|
406
|
+
? null
|
|
407
|
+
: await db.getRepository('executions').findOne({ filterByTk: executionId });
|
|
408
|
+
const reason =
|
|
409
|
+
value<string>(inbox, 'state') === 'quarantined'
|
|
410
|
+
? 'quarantined'
|
|
411
|
+
: executionId == null
|
|
412
|
+
? 'unclaimed'
|
|
413
|
+
: !execution
|
|
414
|
+
? 'execution_missing'
|
|
415
|
+
: null;
|
|
416
|
+
if (reason && quarantined.length < 100)
|
|
417
|
+
quarantined.push({
|
|
418
|
+
requestId: value<Id>(request, 'id'),
|
|
419
|
+
executionId,
|
|
420
|
+
reviewId: value<Id>(request, 'reviewId'),
|
|
421
|
+
reason,
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
return {
|
|
425
|
+
state: value<string>(record, 'state'),
|
|
426
|
+
legacyPending: legacy.filter((review) => value<string>(review, 'status') === 'pending').length,
|
|
427
|
+
legacyRunning: legacy.filter((review) => value<string>(review, 'status') === 'running').length,
|
|
428
|
+
legacyPendingReviews: legacy
|
|
429
|
+
.filter((review) => value<string>(review, 'status') === 'pending')
|
|
430
|
+
.slice(0, 100)
|
|
431
|
+
.map((review) => ({
|
|
432
|
+
legacyReviewId: value<Id>(review, 'id'),
|
|
433
|
+
repositoryId: value<Id>(review, 'repositoryId'),
|
|
434
|
+
reason:
|
|
435
|
+
value<{ migrationBlockedReason?: string } | null>(review, 'metadata')?.migrationBlockedReason ||
|
|
436
|
+
'not_migrated',
|
|
437
|
+
})),
|
|
438
|
+
legacyRunningReviews: legacy
|
|
439
|
+
.filter((review) => value<string>(review, 'status') === 'running')
|
|
440
|
+
.slice(0, 100)
|
|
441
|
+
.map((review) => ({ legacyReviewId: value<Id>(review, 'id') })),
|
|
442
|
+
legacyUncertain: uncertain.length,
|
|
443
|
+
legacyUncertainReviews: uncertain.slice(0, 100).map((review) => ({
|
|
444
|
+
legacyReviewId: value<Id>(review, 'id'),
|
|
445
|
+
repositoryId: value<Id>(review, 'repositoryId'),
|
|
446
|
+
})),
|
|
447
|
+
quarantined,
|
|
448
|
+
orphaned,
|
|
449
|
+
postUnknownReviews,
|
|
450
|
+
legacyPublicationHolds,
|
|
451
|
+
queuedBlockedReviews: queuedBlocked.map((item: Getter) => ({
|
|
452
|
+
inboxId: value<Id>(item, 'id'),
|
|
453
|
+
reviewId: value<Id>(item, 'reviewId'),
|
|
454
|
+
repositoryId: value<Id>(item, 'repositoryId'),
|
|
455
|
+
reason: value<string>(item, 'blockedReason'),
|
|
456
|
+
})),
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
async confirmCutover(actor: Id): Promise<void> {
|
|
461
|
+
await this.cutoverStatus();
|
|
462
|
+
await this.app.db
|
|
463
|
+
.getCollection('gitReviewCutover')
|
|
464
|
+
.model.update(
|
|
465
|
+
{ state: 'ready', confirmedBy: String(actor), confirmedAt: new Date() },
|
|
466
|
+
{ where: { key: 'global', state: 'awaiting_confirmation' } },
|
|
467
|
+
);
|
|
468
|
+
await this.reconcile();
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
private async legacyBlockedProjects(): Promise<{ keys: Set<string>; unknown: boolean }> {
|
|
472
|
+
const db = this.app.db;
|
|
473
|
+
const keys = new Set<string>();
|
|
474
|
+
for (const review of await this.legacyRows()) {
|
|
475
|
+
try {
|
|
476
|
+
const repo = await db
|
|
477
|
+
.getRepository('gitRepositories')
|
|
478
|
+
.findOne({ filterByTk: value<Id>(review, 'repositoryId') });
|
|
479
|
+
if (!repo) return { keys, unknown: true };
|
|
480
|
+
keys.add(await resolveReviewProjectKey(db, repo));
|
|
481
|
+
} catch {
|
|
482
|
+
return { keys, unknown: true };
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
return { keys, unknown: false };
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async recoverLegacy(reviewId: Id, actor: Id): Promise<void> {
|
|
489
|
+
const db = this.app.db;
|
|
490
|
+
if ((await this.cutoverStatus()).state !== 'ready') throw new Error('Review cutover has not been confirmed');
|
|
491
|
+
if (await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } }))
|
|
492
|
+
throw new Error('Review is managed by workflow');
|
|
493
|
+
const [changed] = await db
|
|
494
|
+
.getCollection('gitCodeReviews')
|
|
495
|
+
.model.update(
|
|
496
|
+
{ status: 'failed', error: `Legacy worker stop confirmed by ${String(actor)}`, finishedAt: new Date() },
|
|
497
|
+
{ where: { id: reviewId, status: 'running' } },
|
|
498
|
+
);
|
|
499
|
+
if (changed !== 1) throw new Error('Legacy review is not running');
|
|
500
|
+
await this.reconcile();
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async cancelLegacy(reviewId: Id, actor: Id): Promise<void> {
|
|
504
|
+
const db = this.app.db;
|
|
505
|
+
if ((await this.cutoverStatus()).state !== 'ready') throw new Error('Review cutover has not been confirmed');
|
|
506
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
507
|
+
const review = await db
|
|
508
|
+
.getCollection('gitCodeReviews')
|
|
509
|
+
.model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
510
|
+
if (!review || value<string>(review, 'status') !== 'pending') throw new Error('Legacy review is not pending');
|
|
511
|
+
if (await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId }, transaction }))
|
|
512
|
+
throw new Error('Review is managed by workflow');
|
|
513
|
+
const metadata = value<Record<string, unknown> | null>(review, 'metadata') || {};
|
|
514
|
+
const [changed] = await db.getCollection('gitCodeReviews').model.update(
|
|
515
|
+
{
|
|
516
|
+
status: 'failed',
|
|
517
|
+
error: 'Legacy review canceled during workflow migration',
|
|
518
|
+
finishedAt: new Date(),
|
|
519
|
+
metadata: {
|
|
520
|
+
...metadata,
|
|
521
|
+
migrationCanceledBy: String(actor),
|
|
522
|
+
migrationCanceledAt: new Date().toISOString(),
|
|
523
|
+
},
|
|
524
|
+
},
|
|
525
|
+
{ where: { id: reviewId, status: 'pending' }, transaction },
|
|
526
|
+
);
|
|
527
|
+
if (changed !== 1) throw new Error('Legacy review is no longer pending');
|
|
528
|
+
});
|
|
529
|
+
await this.reconcile();
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async cancelQueued(inboxId: Id, actor: Id): Promise<void> {
|
|
533
|
+
const db = this.app.db;
|
|
534
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
535
|
+
const inbox = await db
|
|
536
|
+
.getCollection('gitReviewInbox')
|
|
537
|
+
.model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
538
|
+
if (!inbox || value<string>(inbox, 'state') !== 'queued') reviewConflict('Review is no longer queued');
|
|
539
|
+
if (await db.getRepository('gitReviewRequests').findOne({ filter: { inboxId }, transaction }))
|
|
540
|
+
reviewConflict('Review has already been dispatched');
|
|
541
|
+
const project = await db.getCollection('gitReviewProjects').model.findOne({
|
|
542
|
+
where: { projectKey: value<string>(inbox, 'projectKey') },
|
|
543
|
+
transaction,
|
|
544
|
+
lock: transaction.LOCK.UPDATE,
|
|
545
|
+
});
|
|
546
|
+
if (project && String(value<Id | null>(project, 'activeInboxId')) === String(inboxId))
|
|
547
|
+
reviewConflict('Review already owns a project reservation');
|
|
548
|
+
await inbox.update(
|
|
549
|
+
{
|
|
550
|
+
state: 'canceled',
|
|
551
|
+
blockedReason: 'canceled_by_operator',
|
|
552
|
+
recoveredBy: String(actor),
|
|
553
|
+
recoveredAt: new Date(),
|
|
554
|
+
},
|
|
555
|
+
{ transaction },
|
|
556
|
+
);
|
|
557
|
+
await db.getRepository('gitCodeReviews').update({
|
|
558
|
+
filterByTk: value<Id>(inbox, 'reviewId'),
|
|
559
|
+
values: { status: 'failed', error: 'Queued review canceled by operator', finishedAt: new Date() },
|
|
560
|
+
transaction,
|
|
561
|
+
});
|
|
562
|
+
});
|
|
563
|
+
await this.reconcile();
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
async recover(requestId: Id, executionId: Id | null, actor: Id): Promise<void> {
|
|
567
|
+
const db = this.app.db;
|
|
568
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
569
|
+
const request = await db
|
|
570
|
+
.getCollection('gitReviewRequests')
|
|
571
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
572
|
+
if (!request || value<boolean>(request, 'fenced')) throw new Error('Review request is unavailable');
|
|
573
|
+
const owner = value<Id | null>(request, 'executionId');
|
|
574
|
+
if ((owner == null) !== (executionId == null) || (owner != null && String(owner) !== String(executionId)))
|
|
575
|
+
throw new Error('Execution does not own request');
|
|
576
|
+
const execution =
|
|
577
|
+
owner == null || !db.getCollection('executions')
|
|
578
|
+
? null
|
|
579
|
+
: await db
|
|
580
|
+
.getCollection('executions')
|
|
581
|
+
.model.findOne({ where: { id: owner }, transaction, lock: transaction.LOCK.UPDATE });
|
|
582
|
+
if (
|
|
583
|
+
execution &&
|
|
584
|
+
(typeof value<unknown>(execution, 'status') !== 'number' || value<number>(execution, 'status') === 0)
|
|
585
|
+
)
|
|
586
|
+
throw new Error('Execution is not terminal');
|
|
587
|
+
const inbox = await db.getCollection('gitReviewInbox').model.findOne({
|
|
588
|
+
where: { id: value<Id>(request, 'inboxId') },
|
|
589
|
+
transaction,
|
|
590
|
+
lock: transaction.LOCK.UPDATE,
|
|
591
|
+
});
|
|
592
|
+
if (!inbox || !['dispatched', 'running', 'quarantined'].includes(value<string>(inbox, 'state')))
|
|
593
|
+
throw new Error('Review is not recoverable');
|
|
594
|
+
if (execution && value<string>(inbox, 'state') !== 'quarantined' && value<number>(execution, 'status') > 0)
|
|
595
|
+
throw new Error('Completed review is not quarantined');
|
|
596
|
+
await db.getCollection('gitReviewProjects').model.findOne({
|
|
597
|
+
where: { projectKey: value<string>(inbox, 'projectKey') },
|
|
598
|
+
transaction,
|
|
599
|
+
lock: transaction.LOCK.UPDATE,
|
|
600
|
+
});
|
|
601
|
+
const review = await db.getCollection('gitCodeReviews').model.findOne({
|
|
602
|
+
where: { id: value<Id>(request, 'reviewId') },
|
|
603
|
+
transaction,
|
|
604
|
+
lock: transaction.LOCK.UPDATE,
|
|
605
|
+
});
|
|
606
|
+
if (
|
|
607
|
+
!review ||
|
|
608
|
+
value<string | null>(request, 'postClaim') ||
|
|
609
|
+
['posting', 'post_unknown', 'post_failed', 'retrying'].includes(value<string>(review, 'postStatus'))
|
|
610
|
+
) {
|
|
611
|
+
reviewConflict('Resolve publication or reset the stopped post attempt before recovery');
|
|
612
|
+
}
|
|
613
|
+
const [fenced] = await db
|
|
614
|
+
.getCollection('gitReviewRequests')
|
|
615
|
+
.model.update({ fenced: true }, { where: { id: requestId, fenced: false }, transaction });
|
|
616
|
+
if (fenced !== 1) throw new Error('Review request could not be fenced');
|
|
617
|
+
await db.getCollection('gitReviewProjects').model.update(
|
|
618
|
+
{ activeInboxId: null },
|
|
619
|
+
{
|
|
620
|
+
where: { projectKey: value<string>(inbox, 'projectKey'), activeInboxId: value<Id>(inbox, 'id') },
|
|
621
|
+
transaction,
|
|
622
|
+
},
|
|
623
|
+
);
|
|
624
|
+
await db.getRepository('gitReviewInbox').update({
|
|
625
|
+
filterByTk: value<Id>(inbox, 'id'),
|
|
626
|
+
values: { state: 'recovered', recoveredBy: String(actor), recoveredAt: new Date() },
|
|
627
|
+
transaction,
|
|
628
|
+
});
|
|
629
|
+
await db.getRepository('gitCodeReviews').update({
|
|
630
|
+
filterByTk: value<Id>(request, 'reviewId'),
|
|
631
|
+
values: { status: 'failed', error: 'Review execution was stopped and recovered', finishedAt: new Date() },
|
|
632
|
+
transaction,
|
|
633
|
+
});
|
|
634
|
+
});
|
|
635
|
+
await this.reconcile();
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
async recoverOrphaned(inboxId: Id, actor: Id): Promise<void> {
|
|
639
|
+
const db = this.app.db;
|
|
640
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
641
|
+
const inbox = await db
|
|
642
|
+
.getCollection('gitReviewInbox')
|
|
643
|
+
.model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
644
|
+
if (!inbox || !['dispatched', 'running', 'quarantined'].includes(value<string>(inbox, 'state')))
|
|
645
|
+
throw new Error('Review is not recoverable');
|
|
646
|
+
if (await db.getRepository('gitReviewRequests').findOne({ filter: { inboxId }, transaction }))
|
|
647
|
+
throw new Error('Review request exists');
|
|
648
|
+
await db
|
|
649
|
+
.getCollection('gitReviewProjects')
|
|
650
|
+
.model.update(
|
|
651
|
+
{ activeInboxId: null },
|
|
652
|
+
{ where: { projectKey: value<string>(inbox, 'projectKey'), activeInboxId: inboxId }, transaction },
|
|
653
|
+
);
|
|
654
|
+
await db.getRepository('gitReviewInbox').update({
|
|
655
|
+
filterByTk: inboxId,
|
|
656
|
+
values: { state: 'recovered', recoveredBy: String(actor), recoveredAt: new Date() },
|
|
657
|
+
transaction,
|
|
658
|
+
});
|
|
659
|
+
await db.getRepository('gitCodeReviews').update({
|
|
660
|
+
filterByTk: value<Id>(inbox, 'reviewId'),
|
|
661
|
+
values: { status: 'failed', error: 'Orphaned review was stopped and recovered', finishedAt: new Date() },
|
|
662
|
+
transaction,
|
|
663
|
+
});
|
|
664
|
+
});
|
|
665
|
+
await this.reconcile();
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
start(): void {
|
|
669
|
+
if (this.timer) return;
|
|
670
|
+
this.timer = setInterval(
|
|
671
|
+
() => this.reconcile().catch((error) => this.app.log?.error?.('Git review reconciliation failed', error)),
|
|
672
|
+
5000,
|
|
673
|
+
);
|
|
674
|
+
this.reconcile().catch((error) => this.app.log?.error?.('Git review reconciliation failed', error));
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
stop(): void {
|
|
678
|
+
if (this.timer) clearInterval(this.timer);
|
|
679
|
+
this.timer = null;
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
async reconcile(): Promise<void> {
|
|
683
|
+
if (this.reconciling) return;
|
|
684
|
+
this.reconciling = true;
|
|
685
|
+
try {
|
|
686
|
+
const status = await this.cutoverStatus();
|
|
687
|
+
if (status.state !== 'ready') return;
|
|
688
|
+
await this.migrateLegacy();
|
|
689
|
+
const db = this.app.db;
|
|
690
|
+
const blocked = await this.legacyBlockedProjects();
|
|
691
|
+
if (blocked.unknown) return;
|
|
692
|
+
const pending = await db
|
|
693
|
+
.getRepository('gitReviewInbox')
|
|
694
|
+
.find({ filter: { state: 'queued' }, sort: ['queuedAt', 'id'] });
|
|
695
|
+
const seen = new Set<string>();
|
|
696
|
+
for (const inbox of pending) {
|
|
697
|
+
const projectKey = value<string>(inbox, 'projectKey');
|
|
698
|
+
if (blocked.keys.has(projectKey)) continue;
|
|
699
|
+
if (seen.has(projectKey)) continue;
|
|
700
|
+
seen.add(projectKey);
|
|
701
|
+
const payload = value<ReviewPayload>(inbox, 'payload');
|
|
702
|
+
try {
|
|
703
|
+
const outcome = await db.sequelize.transaction(async (transaction) => {
|
|
704
|
+
const inboxId = value<number>(inbox, 'id');
|
|
705
|
+
const queued = await db
|
|
706
|
+
.getCollection('gitReviewInbox')
|
|
707
|
+
.model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
708
|
+
if (!queued || value<string>(queued, 'state') !== 'queued') return 'stale';
|
|
709
|
+
const flow = await db.getRepository('gitReviewFlows').findOne({ filterByTk: payload.flowId, transaction });
|
|
710
|
+
if (!flow) {
|
|
711
|
+
await queued.update({ state: 'canceled', blockedReason: 'flow_deleted' }, { transaction });
|
|
712
|
+
await db.getRepository('gitCodeReviews').update({
|
|
713
|
+
filterByTk: value<Id>(queued, 'reviewId'),
|
|
714
|
+
values: {
|
|
715
|
+
status: 'failed',
|
|
716
|
+
error: 'Review flow was deleted before dispatch',
|
|
717
|
+
finishedAt: new Date(),
|
|
718
|
+
},
|
|
719
|
+
transaction,
|
|
720
|
+
});
|
|
721
|
+
return 'canceled';
|
|
722
|
+
}
|
|
723
|
+
if (!value<boolean>(flow, 'enabled')) {
|
|
724
|
+
await queued.update({ blockedReason: 'flow_disabled' }, { transaction });
|
|
725
|
+
return 'blocked';
|
|
726
|
+
}
|
|
727
|
+
if (value<string>(flow, 'workflowKey') !== payload.workflowKey) {
|
|
728
|
+
await queued.update({ blockedReason: 'workflow_binding_changed' }, { transaction });
|
|
729
|
+
return 'blocked';
|
|
730
|
+
}
|
|
731
|
+
const boundId = value<Id | null>(flow, 'workflowId');
|
|
732
|
+
if (boundId) {
|
|
733
|
+
const bound = await db.getRepository('workflows').findOne({ filterByTk: boundId, transaction });
|
|
734
|
+
if (
|
|
735
|
+
!bound ||
|
|
736
|
+
value<{ gitReview?: { draft?: boolean } } | null>(bound, 'options')?.gitReview?.draft === true
|
|
737
|
+
) {
|
|
738
|
+
await queued.update({ blockedReason: 'workflow_setup_incomplete' }, { transaction });
|
|
739
|
+
return 'blocked';
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
const workflow = await db.getRepository('workflows').findOne({
|
|
743
|
+
filter: { key: payload.workflowKey, current: true, enabled: true },
|
|
744
|
+
transaction,
|
|
745
|
+
lock: transaction.LOCK.UPDATE,
|
|
746
|
+
});
|
|
747
|
+
if (!workflow) {
|
|
748
|
+
await queued.update({ blockedReason: 'workflow_disabled' }, { transaction });
|
|
749
|
+
return 'blocked';
|
|
750
|
+
}
|
|
751
|
+
const workflowId = value<Id>(workflow, 'id');
|
|
752
|
+
await this.assertSafeWorkflow(workflowId, payload.postMode, transaction, payload.source.repositoryId);
|
|
753
|
+
const [claimed] = await db
|
|
754
|
+
.getCollection('gitReviewProjects')
|
|
755
|
+
.model.update(
|
|
756
|
+
{ activeInboxId: inboxId },
|
|
757
|
+
{ where: { projectKey, activeInboxId: null, legacyPostReviewId: null }, transaction },
|
|
758
|
+
);
|
|
759
|
+
if (claimed !== 1) {
|
|
760
|
+
if (value<string | null>(queued, 'blockedReason'))
|
|
761
|
+
await queued.update({ blockedReason: null }, { transaction });
|
|
762
|
+
return 'busy';
|
|
763
|
+
}
|
|
764
|
+
await queued.update(
|
|
765
|
+
{ state: 'dispatched', blockedReason: null, payload: { ...payload, workflowId } },
|
|
766
|
+
{ transaction },
|
|
767
|
+
);
|
|
768
|
+
await db.getRepository('gitReviewRequests').create({
|
|
769
|
+
values: {
|
|
770
|
+
inboxId,
|
|
771
|
+
reviewId: value<number>(inbox, 'reviewId'),
|
|
772
|
+
repositoryId: value<number>(inbox, 'repositoryId'),
|
|
773
|
+
flowId: payload.flowId,
|
|
774
|
+
workflowId,
|
|
775
|
+
workflowKey: payload.workflowKey,
|
|
776
|
+
eventType: payload.eventType,
|
|
777
|
+
},
|
|
778
|
+
transaction,
|
|
779
|
+
});
|
|
780
|
+
return 'dispatched';
|
|
781
|
+
});
|
|
782
|
+
if (outcome === 'canceled' || outcome === 'stale') seen.delete(projectKey);
|
|
783
|
+
} catch (error) {
|
|
784
|
+
const reason =
|
|
785
|
+
error instanceof Error && error.message === 'No configured approver can access this repository'
|
|
786
|
+
? 'approver_unavailable'
|
|
787
|
+
: 'workflow_unavailable';
|
|
788
|
+
await db
|
|
789
|
+
.getCollection('gitReviewInbox')
|
|
790
|
+
.model.update({ blockedReason: reason }, { where: { id: value<Id>(inbox, 'id'), state: 'queued' } });
|
|
791
|
+
this.app.log?.warn?.(
|
|
792
|
+
`Git review ${String(value<Id>(inbox, 'reviewId'))} is waiting for a safe workflow revision`,
|
|
793
|
+
);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
} finally {
|
|
797
|
+
this.reconciling = false;
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
private async migrateLegacy(): Promise<void> {
|
|
802
|
+
const db = this.app.db;
|
|
803
|
+
const reviews = db.getRepository('gitCodeReviews');
|
|
804
|
+
const legacy = await reviews.find({ filter: { status: { $in: ['pending', 'running'] } }, sort: ['id'] });
|
|
805
|
+
for (const review of legacy) {
|
|
806
|
+
const reviewId = value<number>(review, 'id');
|
|
807
|
+
if (await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } })) continue;
|
|
808
|
+
if (value<string>(review, 'status') === 'running') continue;
|
|
809
|
+
const metadata = value<Record<string, unknown>>(review, 'metadata') || {};
|
|
810
|
+
try {
|
|
811
|
+
const targetType = value<ReviewTarget>(review, 'targetType');
|
|
812
|
+
const pinnedHead = value<string | null>(review, 'headSha');
|
|
813
|
+
const commitSha = value<string | null>(review, 'commitSha');
|
|
814
|
+
if (targetType === 'branch') throw new Error('Legacy branch review has no pinned base');
|
|
815
|
+
const pinned = pinnedHead || (targetType === 'commit' ? commitSha : null);
|
|
816
|
+
if (!pinned || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(pinned))
|
|
817
|
+
throw new Error('Legacy review has no pinned source commit');
|
|
818
|
+
const legacyActor = value<Id | null>(review, 'createdById');
|
|
819
|
+
const legacyRoles = legacyActor ? await resolveBackgroundReviewRoles(db, legacyActor) : [];
|
|
820
|
+
if (value<string>(review, 'triggeredBy') !== 'poll' && legacyRoles.length !== 1) {
|
|
821
|
+
throw new Error('Legacy review actor has no unambiguous role');
|
|
822
|
+
}
|
|
823
|
+
await this.enqueue({
|
|
824
|
+
legacyReviewId: reviewId,
|
|
825
|
+
repositoryId: value<number>(review, 'repositoryId'),
|
|
826
|
+
flowId: value<number>(review, 'flowId'),
|
|
827
|
+
targetType,
|
|
828
|
+
mrIid: value<number | null>(review, 'mrIid'),
|
|
829
|
+
commitSha,
|
|
830
|
+
branch: value<string | null>(review, 'branch'),
|
|
831
|
+
folderPath: value<string | null>(review, 'folderPath'),
|
|
832
|
+
headSha: pinned,
|
|
833
|
+
extraInstructions: typeof metadata.extraInstructions === 'string' ? metadata.extraInstructions : undefined,
|
|
834
|
+
triggeredBy: value<string>(review, 'triggeredBy') === 'poll' ? 'poll' : 'manual',
|
|
835
|
+
userId: legacyActor,
|
|
836
|
+
actorRoles: legacyRoles,
|
|
837
|
+
});
|
|
838
|
+
} catch (error) {
|
|
839
|
+
const reason = legacyBlockReason(error);
|
|
840
|
+
await db
|
|
841
|
+
.getCollection('gitCodeReviews')
|
|
842
|
+
.model.update(
|
|
843
|
+
{ metadata: { ...metadata, migrationBlockedReason: reason } },
|
|
844
|
+
{ where: { id: reviewId, status: 'pending' } },
|
|
845
|
+
);
|
|
846
|
+
this.app.log?.warn?.(`Legacy review ${reviewId} is waiting for migration: ${reason}`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
private async owned(
|
|
852
|
+
requestId: Id,
|
|
853
|
+
executionId: Id,
|
|
854
|
+
): Promise<{ request: Getter; inbox: Getter; payload: ReviewPayload }> {
|
|
855
|
+
const db = this.app.db;
|
|
856
|
+
const request = await db.getRepository('gitReviewRequests').findOne({ filterByTk: requestId });
|
|
857
|
+
if (
|
|
858
|
+
!request ||
|
|
859
|
+
value<boolean>(request, 'fenced') ||
|
|
860
|
+
String(value<Id>(request, 'executionId')) !== String(executionId)
|
|
861
|
+
)
|
|
862
|
+
throw new Error('Review execution does not own this request');
|
|
863
|
+
const execution = await db.getRepository('executions').findOne({ filterByTk: executionId });
|
|
864
|
+
if (!execution || value<number | null>(execution, 'status') !== 0)
|
|
865
|
+
throw new Error('Review execution is no longer running');
|
|
866
|
+
const inbox = await db.getRepository('gitReviewInbox').findOne({ filterByTk: value<Id>(request, 'inboxId') });
|
|
867
|
+
if (!inbox || !['running', 'dispatched'].includes(value<string>(inbox, 'state')))
|
|
868
|
+
throw new Error('Review request is no longer active');
|
|
869
|
+
const project = await db
|
|
870
|
+
.getRepository('gitReviewProjects')
|
|
871
|
+
.findOne({ filter: { projectKey: value<string>(inbox, 'projectKey') } });
|
|
872
|
+
if (!project || String(value<Id>(project, 'activeInboxId')) !== String(value<Id>(inbox, 'id')))
|
|
873
|
+
throw new Error('Review reservation no longer belongs to this request');
|
|
874
|
+
return { request, inbox, payload: value<ReviewPayload>(inbox, 'payload') };
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
async claim(requestId: Id, executionId: Id): Promise<boolean> {
|
|
878
|
+
const db = this.app.db;
|
|
879
|
+
if ((await this.cutoverStatus()).state !== 'ready') return false;
|
|
880
|
+
return db.sequelize.transaction(async (transaction) => {
|
|
881
|
+
const request = await db
|
|
882
|
+
.getCollection('gitReviewRequests')
|
|
883
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
884
|
+
if (!request || value<boolean>(request, 'fenced')) return false;
|
|
885
|
+
const previous = value<Id | null>(request, 'executionId');
|
|
886
|
+
if (previous != null && String(previous) !== String(executionId)) return false;
|
|
887
|
+
const execution = await db
|
|
888
|
+
.getCollection('executions')
|
|
889
|
+
.model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
890
|
+
if (
|
|
891
|
+
!execution ||
|
|
892
|
+
value<number | null>(execution, 'status') !== 0 ||
|
|
893
|
+
String(value<Id>(execution, 'workflowId')) !== String(value<Id>(request, 'workflowId'))
|
|
894
|
+
)
|
|
895
|
+
return false;
|
|
896
|
+
const context = value<{ data?: { id?: Id } }>(execution, 'context');
|
|
897
|
+
if (String(context?.data?.id) !== String(requestId)) return false;
|
|
898
|
+
const inbox = await db
|
|
899
|
+
.getCollection('gitReviewInbox')
|
|
900
|
+
.model.findOne({ where: { id: value<Id>(request, 'inboxId') }, transaction, lock: transaction.LOCK.UPDATE });
|
|
901
|
+
if (!inbox || value<string>(inbox, 'state') !== (previous == null ? 'dispatched' : 'running')) return false;
|
|
902
|
+
const project = await db.getCollection('gitReviewProjects').model.findOne({
|
|
903
|
+
where: { projectKey: value<string>(inbox, 'projectKey') },
|
|
904
|
+
transaction,
|
|
905
|
+
lock: transaction.LOCK.UPDATE,
|
|
906
|
+
});
|
|
907
|
+
if (!project || String(value<Id>(project, 'activeInboxId')) !== String(value<Id>(inbox, 'id'))) return false;
|
|
908
|
+
if (previous != null) return true;
|
|
909
|
+
const [count] = await db
|
|
910
|
+
.getCollection('gitReviewRequests')
|
|
911
|
+
.model.update({ executionId }, { where: { id: requestId, executionId: null, fenced: false }, transaction });
|
|
912
|
+
if (count !== 1) return false;
|
|
913
|
+
await db
|
|
914
|
+
.getRepository('gitReviewInbox')
|
|
915
|
+
.update({ filterByTk: value<Id>(inbox, 'id'), values: { state: 'running' }, transaction });
|
|
916
|
+
await db.getRepository('gitCodeReviews').update({
|
|
917
|
+
filterByTk: value<Id>(request, 'reviewId'),
|
|
918
|
+
values: {
|
|
919
|
+
status: 'running',
|
|
920
|
+
startedAt: new Date(),
|
|
921
|
+
metadata: { workflowManaged: true, workflowExecutionId: String(executionId) },
|
|
922
|
+
},
|
|
923
|
+
transaction,
|
|
924
|
+
});
|
|
925
|
+
return true;
|
|
926
|
+
});
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
async prepareContext(requestId: Id, executionId: Id) {
|
|
930
|
+
const { request, payload } = await this.owned(requestId, executionId);
|
|
931
|
+
await this.assertActor(payload);
|
|
932
|
+
const repo = await this.app.db
|
|
933
|
+
.getRepository('gitRepositories')
|
|
934
|
+
.findOne({ filterByTk: payload.source.repositoryId });
|
|
935
|
+
if (!repo) throw new Error('Repository not found');
|
|
936
|
+
const diff = await readPinnedReviewSource(this.app.db, repo, payload.source);
|
|
937
|
+
const limitations: string[] = [];
|
|
938
|
+
if (payload.source.targetType === 'mr')
|
|
939
|
+
limitations.push('Provider comparison patches may omit binary content or truncate large files.');
|
|
940
|
+
if (/Binary files .* differ|GIT binary patch/.test(diff))
|
|
941
|
+
limitations.push('Binary file changes do not include readable source.');
|
|
942
|
+
return {
|
|
943
|
+
requestId,
|
|
944
|
+
reviewId: value<Id>(request, 'reviewId'),
|
|
945
|
+
...payload.source,
|
|
946
|
+
userId: payload.userId,
|
|
947
|
+
diff,
|
|
948
|
+
coverage: { complete: limitations.length === 0, limitations },
|
|
949
|
+
instructions: payload.instructions,
|
|
950
|
+
postMode: payload.postMode,
|
|
951
|
+
};
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
private async assertActor(payload: ReviewPayload): Promise<void> {
|
|
955
|
+
if (!payload.userId || !payload.actorRoles?.length) throw new Error('Review actor is missing');
|
|
956
|
+
const current = await resolveBackgroundReviewRoles(this.app.db, payload.userId);
|
|
957
|
+
if (payload.actorRoles.some((role) => !current.includes(role))) throw new Error('Review actor roles changed');
|
|
958
|
+
const action = payload.source.targetType === 'mr' ? 'mergeRequestDetail' : 'fileContent';
|
|
959
|
+
for (const required of ['triggerReview', action]) {
|
|
960
|
+
if (
|
|
961
|
+
!(await hasRepositoryAccess({
|
|
962
|
+
acl: this.app.acl,
|
|
963
|
+
roles: payload.actorRoles,
|
|
964
|
+
repositoryId: payload.source.repositoryId,
|
|
965
|
+
action: required,
|
|
966
|
+
}))
|
|
967
|
+
)
|
|
968
|
+
throw new Error('Review actor no longer has repository access');
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
async saveResult(requestId: Id, executionId: Id, markdown: string): Promise<string> {
|
|
973
|
+
if (typeof markdown !== 'string' || !markdown.trim() || Buffer.byteLength(markdown) > 200_000)
|
|
974
|
+
throw new Error('Invalid review result');
|
|
975
|
+
const { request, payload } = await this.owned(requestId, executionId);
|
|
976
|
+
const hash = fingerprint(markdown);
|
|
977
|
+
const existing = value<string | null>(request, 'resultFingerprint');
|
|
978
|
+
if (existing && existing !== hash) throw new Error('Review result is immutable');
|
|
979
|
+
const persist = async (transaction: Transaction) => {
|
|
980
|
+
const lockedRequest = await this.app.db
|
|
981
|
+
.getCollection('gitReviewRequests')
|
|
982
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
983
|
+
if (
|
|
984
|
+
!lockedRequest ||
|
|
985
|
+
value<boolean>(lockedRequest, 'fenced') ||
|
|
986
|
+
String(value<Id>(lockedRequest, 'executionId')) !== String(executionId)
|
|
987
|
+
)
|
|
988
|
+
throw new Error('Review execution lost ownership');
|
|
989
|
+
const lockedFingerprint = value<string | null>(lockedRequest, 'resultFingerprint');
|
|
990
|
+
if (lockedFingerprint && lockedFingerprint !== hash) throw new Error('Review result is immutable');
|
|
991
|
+
const execution = await this.app.db
|
|
992
|
+
.getCollection('executions')
|
|
993
|
+
.model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
994
|
+
const inbox = await this.app.db
|
|
995
|
+
.getCollection('gitReviewInbox')
|
|
996
|
+
.model.findOne({ where: { id: value<Id>(request, 'inboxId') }, transaction, lock: transaction.LOCK.UPDATE });
|
|
997
|
+
if (
|
|
998
|
+
!execution ||
|
|
999
|
+
value<number | null>(execution, 'status') !== 0 ||
|
|
1000
|
+
!inbox ||
|
|
1001
|
+
value<string>(inbox, 'state') !== 'running'
|
|
1002
|
+
)
|
|
1003
|
+
throw new Error('Review execution is no longer active');
|
|
1004
|
+
if (lockedFingerprint === hash) return;
|
|
1005
|
+
const [updated] = await this.app.db
|
|
1006
|
+
.getCollection('gitReviewRequests')
|
|
1007
|
+
.model.update(
|
|
1008
|
+
{ resultFingerprint: hash },
|
|
1009
|
+
{ where: { id: requestId, executionId, fenced: false }, transaction },
|
|
1010
|
+
);
|
|
1011
|
+
if (updated !== 1) throw new Error('Review execution lost ownership');
|
|
1012
|
+
await this.app.db.getRepository('gitCodeReviews').update({
|
|
1013
|
+
filterByTk: value<Id>(request, 'reviewId'),
|
|
1014
|
+
values: {
|
|
1015
|
+
reviewMarkdown: markdown,
|
|
1016
|
+
status: 'completed',
|
|
1017
|
+
postStatus:
|
|
1018
|
+
payload.source.targetType === 'mr' && payload.postMode !== 'disabled' ? 'pending_approval' : 'skipped',
|
|
1019
|
+
finishedAt: new Date(),
|
|
1020
|
+
},
|
|
1021
|
+
transaction,
|
|
1022
|
+
});
|
|
1023
|
+
};
|
|
1024
|
+
const sequelize = this.app.db.sequelize;
|
|
1025
|
+
if (sequelize.getDialect() !== 'sqlite') {
|
|
1026
|
+
await sequelize.transaction(persist);
|
|
1027
|
+
return hash;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// SQLite must acquire its write reservation before the ownership reads, so a concurrent writer cannot
|
|
1031
|
+
// invalidate a deferred read snapshot when this transaction later writes. Retry only before a commit attempt.
|
|
1032
|
+
const isBusy = (error: unknown) => {
|
|
1033
|
+
const detail = error as { code?: string; original?: { code?: string }; parent?: { code?: string } } | null;
|
|
1034
|
+
return [detail?.code, detail?.original?.code, detail?.parent?.code].includes('SQLITE_BUSY');
|
|
1035
|
+
};
|
|
1036
|
+
for (let attempt = 0; ; attempt++) {
|
|
1037
|
+
let transaction: Transaction;
|
|
1038
|
+
try {
|
|
1039
|
+
transaction = await sequelize.transaction({ type: Transaction.TYPES.IMMEDIATE });
|
|
1040
|
+
} catch (error) {
|
|
1041
|
+
if (!isBusy(error) || attempt >= 7) throw error;
|
|
1042
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
|
|
1043
|
+
continue;
|
|
1044
|
+
}
|
|
1045
|
+
try {
|
|
1046
|
+
await persist(transaction);
|
|
1047
|
+
} catch (error) {
|
|
1048
|
+
await transaction.rollback();
|
|
1049
|
+
if (!isBusy(error) || attempt >= 7) throw error;
|
|
1050
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
|
|
1051
|
+
continue;
|
|
1052
|
+
}
|
|
1053
|
+
await transaction.commit();
|
|
1054
|
+
return hash;
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
private async startPublication(
|
|
1059
|
+
requestId: Id,
|
|
1060
|
+
executionId: Id,
|
|
1061
|
+
inboxId: Id,
|
|
1062
|
+
reviewId: Id,
|
|
1063
|
+
payload: ReviewPayload,
|
|
1064
|
+
hash: string,
|
|
1065
|
+
token: string,
|
|
1066
|
+
mode: 'initial' | 'retry',
|
|
1067
|
+
start: () => ReturnType<typeof fetch>,
|
|
1068
|
+
): Promise<{ response: ReturnType<typeof fetch> }> {
|
|
1069
|
+
const db = this.app.db;
|
|
1070
|
+
const options = db.sequelize.getDialect() === 'sqlite' ? { type: Transaction.TYPES.IMMEDIATE } : {};
|
|
1071
|
+
return db.sequelize.transaction(options, async (transaction) => {
|
|
1072
|
+
const request = await db.getCollection('gitReviewRequests').model.findOne({
|
|
1073
|
+
where: { id: requestId },
|
|
1074
|
+
transaction,
|
|
1075
|
+
lock: transaction.LOCK.UPDATE,
|
|
1076
|
+
});
|
|
1077
|
+
const execution = await db.getCollection('executions').model.findOne({
|
|
1078
|
+
where: { id: executionId },
|
|
1079
|
+
transaction,
|
|
1080
|
+
lock: transaction.LOCK.UPDATE,
|
|
1081
|
+
});
|
|
1082
|
+
const inbox = await db.getCollection('gitReviewInbox').model.findOne({
|
|
1083
|
+
where: { id: inboxId },
|
|
1084
|
+
transaction,
|
|
1085
|
+
lock: transaction.LOCK.UPDATE,
|
|
1086
|
+
});
|
|
1087
|
+
const project = await db.getCollection('gitReviewProjects').model.findOne({
|
|
1088
|
+
where: { projectKey: payload.source.projectKey },
|
|
1089
|
+
transaction,
|
|
1090
|
+
lock: transaction.LOCK.UPDATE,
|
|
1091
|
+
});
|
|
1092
|
+
const review = await db.getCollection('gitCodeReviews').model.findOne({
|
|
1093
|
+
where: { id: reviewId },
|
|
1094
|
+
transaction,
|
|
1095
|
+
lock: transaction.LOCK.UPDATE,
|
|
1096
|
+
});
|
|
1097
|
+
const currentPayload = inbox && value<ReviewPayload>(inbox, 'payload');
|
|
1098
|
+
const context = execution && value<{ data?: { id?: Id } }>(execution, 'context');
|
|
1099
|
+
if (
|
|
1100
|
+
!request ||
|
|
1101
|
+
value<boolean>(request, 'fenced') ||
|
|
1102
|
+
!value<boolean>(request, 'aiSettled') ||
|
|
1103
|
+
value<string | null>(request, 'postClaim') !== token ||
|
|
1104
|
+
String(value<Id>(request, 'executionId')) !== String(executionId) ||
|
|
1105
|
+
String(value<Id>(request, 'inboxId')) !== String(inboxId) ||
|
|
1106
|
+
String(value<Id>(request, 'reviewId')) !== String(reviewId) ||
|
|
1107
|
+
value<string>(request, 'resultFingerprint') !== hash ||
|
|
1108
|
+
!execution ||
|
|
1109
|
+
String(value<Id>(execution, 'workflowId')) !== String(value<Id>(request, 'workflowId')) ||
|
|
1110
|
+
String(context?.data?.id) !== String(requestId) ||
|
|
1111
|
+
(mode === 'initial'
|
|
1112
|
+
? value<number | null>(execution, 'status') !== 0
|
|
1113
|
+
: typeof value<unknown>(execution, 'status') !== 'number' || value<number>(execution, 'status') === 0) ||
|
|
1114
|
+
!inbox ||
|
|
1115
|
+
(mode === 'initial' && value<string>(inbox, 'state') !== 'running') ||
|
|
1116
|
+
!currentPayload ||
|
|
1117
|
+
currentPayload.postMode !== payload.postMode ||
|
|
1118
|
+
JSON.stringify(currentPayload.source) !== JSON.stringify(payload.source) ||
|
|
1119
|
+
!project ||
|
|
1120
|
+
String(value<Id | null>(project, 'activeInboxId')) !== String(inboxId) ||
|
|
1121
|
+
value<Id | null>(project, 'legacyPostReviewId') != null ||
|
|
1122
|
+
!review ||
|
|
1123
|
+
value<string>(review, 'status') !== 'completed' ||
|
|
1124
|
+
value<string>(review, 'postStatus') !== (mode === 'initial' ? 'posting' : 'retrying') ||
|
|
1125
|
+
String(value<Id>(review, 'repositoryId')) !== String(payload.source.repositoryId) ||
|
|
1126
|
+
value<string>(review, 'targetType') !== 'mr' ||
|
|
1127
|
+
String(value<Id | null>(review, 'mrIid')) !== String(payload.source.mrIid) ||
|
|
1128
|
+
value<string>(review, 'headSha') !== payload.source.headSha ||
|
|
1129
|
+
fingerprint(value<string>(review, 'reviewMarkdown') || '') !== hash
|
|
1130
|
+
)
|
|
1131
|
+
reviewConflict('Review publication claim changed');
|
|
1132
|
+
|
|
1133
|
+
// Lock the evidence as well as the execution, so the checked LLM and approval jobs cannot be changed before POST starts.
|
|
1134
|
+
const nodes = await db.getCollection('flow_nodes').model.findAll({
|
|
1135
|
+
where: { workflowId: value<Id>(request, 'workflowId') },
|
|
1136
|
+
transaction,
|
|
1137
|
+
lock: transaction.LOCK.UPDATE,
|
|
1138
|
+
});
|
|
1139
|
+
const llms = nodes.filter((node: Getter) => value<string>(node, 'type') === 'git-review-llm');
|
|
1140
|
+
if (!llms.length) reviewConflict('Review publication claim changed');
|
|
1141
|
+
for (const node of llms) {
|
|
1142
|
+
const jobs = await db.getCollection('jobs').model.findAll({
|
|
1143
|
+
where: { executionId, nodeId: value<Id>(node, 'id') },
|
|
1144
|
+
transaction,
|
|
1145
|
+
lock: transaction.LOCK.UPDATE,
|
|
1146
|
+
});
|
|
1147
|
+
if (jobs.length !== 1 || value<number>(jobs[0], 'status') !== 1)
|
|
1148
|
+
reviewConflict('Review publication claim changed');
|
|
1149
|
+
}
|
|
1150
|
+
if (payload.postMode === 'manual') {
|
|
1151
|
+
const manual = nodes.filter((node: Getter) => value<string>(node, 'type') === 'manual');
|
|
1152
|
+
if (manual.length !== 1) reviewConflict('Review publication claim changed');
|
|
1153
|
+
const jobs = await db.getCollection('jobs').model.findAll({
|
|
1154
|
+
where: { executionId, nodeId: value<Id>(manual[0], 'id') },
|
|
1155
|
+
transaction,
|
|
1156
|
+
lock: transaction.LOCK.UPDATE,
|
|
1157
|
+
});
|
|
1158
|
+
const result = jobs[0] && value<{ _?: string; review?: { fingerprint?: string } }>(jobs[0], 'result');
|
|
1159
|
+
if (
|
|
1160
|
+
jobs.length !== 1 ||
|
|
1161
|
+
value<number>(jobs[0], 'status') !== 1 ||
|
|
1162
|
+
result?._ !== 'approve' ||
|
|
1163
|
+
result.review?.fingerprint !== hash
|
|
1164
|
+
)
|
|
1165
|
+
reviewConflict('Review publication claim changed');
|
|
1166
|
+
const workflow = await db.getCollection('workflows').model.findOne({
|
|
1167
|
+
where: { id: value<Id>(request, 'workflowId') },
|
|
1168
|
+
transaction,
|
|
1169
|
+
lock: transaction.LOCK.UPDATE,
|
|
1170
|
+
});
|
|
1171
|
+
const options = workflow && value<{ gitReview?: { approverIds?: Id[] } }>(workflow, 'options');
|
|
1172
|
+
const assignees = options?.gitReview?.approverIds;
|
|
1173
|
+
const tasks = await db.getCollection('workflowManualTasks').model.findAll({
|
|
1174
|
+
where: {
|
|
1175
|
+
executionId,
|
|
1176
|
+
workflowId: value<Id>(request, 'workflowId'),
|
|
1177
|
+
nodeId: value<Id>(manual[0], 'id'),
|
|
1178
|
+
jobId: value<Id>(jobs[0], 'id'),
|
|
1179
|
+
status: 1,
|
|
1180
|
+
},
|
|
1181
|
+
transaction,
|
|
1182
|
+
lock: transaction.LOCK.UPDATE,
|
|
1183
|
+
});
|
|
1184
|
+
if (
|
|
1185
|
+
!Array.isArray(assignees) ||
|
|
1186
|
+
!tasks.some((task: Getter) => {
|
|
1187
|
+
const decision = value<{ _?: string; review?: { fingerprint?: string } }>(task, 'result');
|
|
1188
|
+
return (
|
|
1189
|
+
decision?._ === 'approve' &&
|
|
1190
|
+
decision.review?.fingerprint === hash &&
|
|
1191
|
+
assignees.some((id) => String(id) === String(value<Id>(task, 'userId')))
|
|
1192
|
+
);
|
|
1193
|
+
})
|
|
1194
|
+
)
|
|
1195
|
+
reviewConflict('Review publication claim changed');
|
|
1196
|
+
}
|
|
1197
|
+
// Fetch starts before releasing the reservation locks; the response is deliberately awaited after commit.
|
|
1198
|
+
const response = start();
|
|
1199
|
+
response.catch(() => undefined);
|
|
1200
|
+
return { response };
|
|
1201
|
+
});
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
async publish(
|
|
1205
|
+
requestId: Id,
|
|
1206
|
+
executionId: Id,
|
|
1207
|
+
approvedFingerprint: string,
|
|
1208
|
+
): Promise<{ status: 'posted' | 'skipped' | 'in_progress' }> {
|
|
1209
|
+
const { request, inbox, payload } = await this.owned(requestId, executionId);
|
|
1210
|
+
await this.assertActor(payload);
|
|
1211
|
+
const db = this.app.db;
|
|
1212
|
+
const review = await db.getRepository('gitCodeReviews').findOne({ filterByTk: value<Id>(request, 'reviewId') });
|
|
1213
|
+
if (!review) throw new Error('Review not found');
|
|
1214
|
+
const markdown = value<string>(review, 'reviewMarkdown');
|
|
1215
|
+
if (
|
|
1216
|
+
!markdown ||
|
|
1217
|
+
fingerprint(markdown) !== approvedFingerprint ||
|
|
1218
|
+
value<string>(request, 'resultFingerprint') !== approvedFingerprint
|
|
1219
|
+
)
|
|
1220
|
+
throw new Error('Approved review content changed');
|
|
1221
|
+
if (payload.source.targetType !== 'mr' || payload.postMode === 'disabled') return { status: 'skipped' };
|
|
1222
|
+
if (payload.postMode === 'manual') {
|
|
1223
|
+
const integration = (this.app.pm.get('plugin-workflow-git-review') ||
|
|
1224
|
+
this.app.pm.get('workflow-git-review')) as unknown as
|
|
1225
|
+
| {
|
|
1226
|
+
enabled?: boolean;
|
|
1227
|
+
assertManualApproval?: (workflowId: Id, executionId: Id, fingerprint: string) => Promise<void>;
|
|
1228
|
+
}
|
|
1229
|
+
| undefined;
|
|
1230
|
+
if (integration?.enabled !== true || !integration.assertManualApproval)
|
|
1231
|
+
reviewConflict('Review approval verifier is unavailable');
|
|
1232
|
+
await integration.assertManualApproval(value<Id>(request, 'workflowId'), executionId, approvedFingerprint);
|
|
1233
|
+
}
|
|
1234
|
+
const reviewId = value<Id>(request, 'reviewId');
|
|
1235
|
+
const inboxId = value<Id>(inbox, 'id');
|
|
1236
|
+
const token = randomUUID();
|
|
1237
|
+
const claim = async (transaction: Transaction): Promise<'posted' | 'in_progress' | 'claimed'> => {
|
|
1238
|
+
const lockedRequest = await db.getCollection('gitReviewRequests').model.findOne({
|
|
1239
|
+
where: { id: requestId },
|
|
1240
|
+
transaction,
|
|
1241
|
+
lock: transaction.LOCK.UPDATE,
|
|
1242
|
+
});
|
|
1243
|
+
const lockedExecution = await db.getCollection('executions').model.findOne({
|
|
1244
|
+
where: { id: executionId },
|
|
1245
|
+
transaction,
|
|
1246
|
+
lock: transaction.LOCK.UPDATE,
|
|
1247
|
+
});
|
|
1248
|
+
const lockedInbox = await db.getCollection('gitReviewInbox').model.findOne({
|
|
1249
|
+
where: { id: inboxId },
|
|
1250
|
+
transaction,
|
|
1251
|
+
lock: transaction.LOCK.UPDATE,
|
|
1252
|
+
});
|
|
1253
|
+
const project = await db.getCollection('gitReviewProjects').model.findOne({
|
|
1254
|
+
where: { projectKey: payload.source.projectKey },
|
|
1255
|
+
transaction,
|
|
1256
|
+
lock: transaction.LOCK.UPDATE,
|
|
1257
|
+
});
|
|
1258
|
+
const lockedReview = await db.getCollection('gitCodeReviews').model.findOne({
|
|
1259
|
+
where: { id: reviewId },
|
|
1260
|
+
transaction,
|
|
1261
|
+
lock: transaction.LOCK.UPDATE,
|
|
1262
|
+
});
|
|
1263
|
+
if (
|
|
1264
|
+
!lockedRequest ||
|
|
1265
|
+
value<boolean>(lockedRequest, 'fenced') ||
|
|
1266
|
+
!value<boolean>(lockedRequest, 'aiSettled') ||
|
|
1267
|
+
String(value<Id>(lockedRequest, 'executionId')) !== String(executionId) ||
|
|
1268
|
+
value<string>(lockedRequest, 'resultFingerprint') !== approvedFingerprint ||
|
|
1269
|
+
!lockedExecution ||
|
|
1270
|
+
value<number | null>(lockedExecution, 'status') !== 0 ||
|
|
1271
|
+
String(value<Id>(lockedExecution, 'workflowId')) !== String(value<Id>(lockedRequest, 'workflowId')) ||
|
|
1272
|
+
!lockedInbox ||
|
|
1273
|
+
value<string>(lockedInbox, 'state') !== 'running' ||
|
|
1274
|
+
!project ||
|
|
1275
|
+
String(value<Id | null>(project, 'activeInboxId')) !== String(inboxId) ||
|
|
1276
|
+
value<Id | null>(project, 'legacyPostReviewId') != null ||
|
|
1277
|
+
!lockedReview ||
|
|
1278
|
+
value<string>(lockedReview, 'status') !== 'completed' ||
|
|
1279
|
+
fingerprint(value<string>(lockedReview, 'reviewMarkdown') || '') !== approvedFingerprint
|
|
1280
|
+
)
|
|
1281
|
+
reviewConflict('Review publication is already in progress or unavailable');
|
|
1282
|
+
const postStatus = value<string>(lockedReview, 'postStatus');
|
|
1283
|
+
if (value<string | null>(lockedRequest, 'postClaim')) return 'in_progress' as const;
|
|
1284
|
+
if (postStatus === 'posted') {
|
|
1285
|
+
if (value<Id | null>(lockedReview, 'postedNoteId') == null)
|
|
1286
|
+
reviewConflict('Review publication receipt is unavailable');
|
|
1287
|
+
return 'posted' as const;
|
|
1288
|
+
}
|
|
1289
|
+
if (['posting', 'post_unknown', 'post_failed', 'retrying'].includes(postStatus)) return 'in_progress' as const;
|
|
1290
|
+
if (postStatus !== 'pending_approval') reviewConflict('Review publication is already in progress or unavailable');
|
|
1291
|
+
await lockedRequest.update({ postClaim: token, postClaimedAt: new Date() }, { transaction });
|
|
1292
|
+
await lockedReview.update({ postStatus: 'posting' }, { transaction });
|
|
1293
|
+
return 'claimed';
|
|
1294
|
+
};
|
|
1295
|
+
let admission: 'posted' | 'in_progress' | 'claimed';
|
|
1296
|
+
if (db.sequelize.getDialect() !== 'sqlite') {
|
|
1297
|
+
admission = await db.sequelize.transaction(claim);
|
|
1298
|
+
} else {
|
|
1299
|
+
const isBusy = (error: unknown) => {
|
|
1300
|
+
const detail = error as { code?: string; original?: { code?: string }; parent?: { code?: string } } | null;
|
|
1301
|
+
return [detail?.code, detail?.original?.code, detail?.parent?.code].includes('SQLITE_BUSY');
|
|
1302
|
+
};
|
|
1303
|
+
// Only the database claim is retryable. A commit failure is ambiguous and must not start or retry the POST.
|
|
1304
|
+
for (let attempt = 0; ; attempt++) {
|
|
1305
|
+
let transaction: Transaction;
|
|
1306
|
+
try {
|
|
1307
|
+
transaction = await db.sequelize.transaction({ type: Transaction.TYPES.IMMEDIATE });
|
|
1308
|
+
} catch (error) {
|
|
1309
|
+
if (!isBusy(error) || attempt >= 7) throw error;
|
|
1310
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
|
|
1311
|
+
continue;
|
|
1312
|
+
}
|
|
1313
|
+
try {
|
|
1314
|
+
admission = await claim(transaction);
|
|
1315
|
+
} catch (error) {
|
|
1316
|
+
await transaction.rollback();
|
|
1317
|
+
if (!isBusy(error) || attempt >= 7) throw error;
|
|
1318
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(25 * 2 ** attempt, 400)));
|
|
1319
|
+
continue;
|
|
1320
|
+
}
|
|
1321
|
+
await transaction.commit();
|
|
1322
|
+
break;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
if (admission !== 'claimed') return { status: admission };
|
|
1326
|
+
try {
|
|
1327
|
+
const repo = await db.getRepository('gitRepositories').findOne({ filterByTk: payload.source.repositoryId });
|
|
1328
|
+
if (!repo) throw new Error('Repository not found');
|
|
1329
|
+
await assertCurrentMrHead(db, repo, payload.source);
|
|
1330
|
+
const marker = `<!-- git-review:${String(requestId)}:${approvedFingerprint} -->`;
|
|
1331
|
+
const noteId = await publishPinnedReview(db, repo, payload.source, markdown, marker, async (start) => {
|
|
1332
|
+
await this.assertActor(payload);
|
|
1333
|
+
return this.startPublication(
|
|
1334
|
+
requestId,
|
|
1335
|
+
executionId,
|
|
1336
|
+
inboxId,
|
|
1337
|
+
reviewId,
|
|
1338
|
+
payload,
|
|
1339
|
+
approvedFingerprint,
|
|
1340
|
+
token,
|
|
1341
|
+
'initial',
|
|
1342
|
+
start,
|
|
1343
|
+
);
|
|
1344
|
+
});
|
|
1345
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1346
|
+
const current = await db.getCollection('gitReviewRequests').model.findOne({
|
|
1347
|
+
where: { id: requestId },
|
|
1348
|
+
transaction,
|
|
1349
|
+
lock: transaction.LOCK.UPDATE,
|
|
1350
|
+
});
|
|
1351
|
+
const currentReview = await db.getCollection('gitCodeReviews').model.findOne({
|
|
1352
|
+
where: { id: reviewId },
|
|
1353
|
+
transaction,
|
|
1354
|
+
lock: transaction.LOCK.UPDATE,
|
|
1355
|
+
});
|
|
1356
|
+
if (
|
|
1357
|
+
!current ||
|
|
1358
|
+
value<boolean>(current, 'fenced') ||
|
|
1359
|
+
value<string | null>(current, 'postClaim') !== token ||
|
|
1360
|
+
value<string>(current, 'resultFingerprint') !== approvedFingerprint ||
|
|
1361
|
+
!currentReview ||
|
|
1362
|
+
value<string>(currentReview, 'postStatus') !== 'posting' ||
|
|
1363
|
+
fingerprint(value<string>(currentReview, 'reviewMarkdown') || '') !== approvedFingerprint
|
|
1364
|
+
)
|
|
1365
|
+
reviewConflict('Review publication claim changed');
|
|
1366
|
+
await currentReview.update({ postStatus: 'posted', postedNoteId: noteId, error: null }, { transaction });
|
|
1367
|
+
await current.update({ postClaim: null, postClaimedAt: null }, { transaction });
|
|
1368
|
+
});
|
|
1369
|
+
return { status: 'posted' };
|
|
1370
|
+
} catch (error) {
|
|
1371
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1372
|
+
const current = await db.getCollection('gitReviewRequests').model.findOne({
|
|
1373
|
+
where: { id: requestId },
|
|
1374
|
+
transaction,
|
|
1375
|
+
lock: transaction.LOCK.UPDATE,
|
|
1376
|
+
});
|
|
1377
|
+
if (!current || value<string | null>(current, 'postClaim') !== token) return;
|
|
1378
|
+
await db
|
|
1379
|
+
.getCollection('gitCodeReviews')
|
|
1380
|
+
.model.update(
|
|
1381
|
+
{ postStatus: 'post_unknown', error: 'Review publication outcome is unknown' },
|
|
1382
|
+
{ where: { id: reviewId, postStatus: 'posting' }, transaction },
|
|
1383
|
+
);
|
|
1384
|
+
});
|
|
1385
|
+
throw error;
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
|
|
1389
|
+
async retryPost(
|
|
1390
|
+
reviewId: Id,
|
|
1391
|
+
actor: Id,
|
|
1392
|
+
roles: string[],
|
|
1393
|
+
allowResend: boolean,
|
|
1394
|
+
): Promise<{ status: 'posted' | 'observed' | 'unknown'; postedNoteId?: string; canResend: boolean }> {
|
|
1395
|
+
const db = this.app.db;
|
|
1396
|
+
const review = await db.getRepository('gitCodeReviews').findOne({ filterByTk: reviewId });
|
|
1397
|
+
if (!review) reviewConflict('Review not found');
|
|
1398
|
+
const repositoryId = value<Id>(review, 'repositoryId');
|
|
1399
|
+
const currentRoles = await resolveBackgroundReviewRoles(db, actor);
|
|
1400
|
+
if (
|
|
1401
|
+
!roles.length ||
|
|
1402
|
+
roles.some((role) => !currentRoles.includes(role)) ||
|
|
1403
|
+
!(await hasRepositoryAccess({ acl: this.app.acl, roles, repositoryId, action: 'reviewWorkflowRetryPost' }))
|
|
1404
|
+
) {
|
|
1405
|
+
const error = new Error('Permission denied') as Error & { status: number };
|
|
1406
|
+
error.status = 403;
|
|
1407
|
+
throw error;
|
|
1408
|
+
}
|
|
1409
|
+
const inbox = await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } });
|
|
1410
|
+
const request =
|
|
1411
|
+
inbox && (await db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: value<Id>(inbox, 'id') } }));
|
|
1412
|
+
if (!inbox || !request || value<boolean>(request, 'fenced') || !value<boolean>(request, 'aiSettled'))
|
|
1413
|
+
reviewConflict('Review is not settled or is no longer available');
|
|
1414
|
+
const executionId = value<Id | null>(request, 'executionId');
|
|
1415
|
+
if (executionId == null) reviewConflict('Review execution is unavailable');
|
|
1416
|
+
const execution = await db.getRepository('executions').findOne({ filterByTk: executionId });
|
|
1417
|
+
if (
|
|
1418
|
+
!execution ||
|
|
1419
|
+
typeof value<unknown>(execution, 'status') !== 'number' ||
|
|
1420
|
+
value<number>(execution, 'status') === 0
|
|
1421
|
+
)
|
|
1422
|
+
reviewConflict('Review execution is not terminal');
|
|
1423
|
+
const payload = value<ReviewPayload>(inbox, 'payload');
|
|
1424
|
+
if (!payload || payload.source.targetType !== 'mr' || payload.postMode === 'disabled')
|
|
1425
|
+
reviewConflict('Review cannot be published');
|
|
1426
|
+
const markdown = value<string>(review, 'reviewMarkdown');
|
|
1427
|
+
const hash = value<string | null>(request, 'resultFingerprint');
|
|
1428
|
+
if (!markdown || !hash || fingerprint(markdown) !== hash) reviewConflict('Approved review content changed');
|
|
1429
|
+
const integration = (this.app.pm.get('plugin-workflow-git-review') ||
|
|
1430
|
+
this.app.pm.get('workflow-git-review')) as unknown as
|
|
1431
|
+
| {
|
|
1432
|
+
enabled?: boolean;
|
|
1433
|
+
assertManualApproval?: (workflowId: Id, executionId: Id, fingerprint: string) => Promise<void>;
|
|
1434
|
+
}
|
|
1435
|
+
| undefined;
|
|
1436
|
+
if (integration?.enabled !== true) reviewConflict('Git review workflow integration is unavailable');
|
|
1437
|
+
await this.assertSafeWorkflow(value<Id>(request, 'workflowId'), payload.postMode, undefined, repositoryId);
|
|
1438
|
+
if (payload.postMode === 'manual') {
|
|
1439
|
+
if (!integration.assertManualApproval) reviewConflict('Review approval verifier is unavailable');
|
|
1440
|
+
await integration.assertManualApproval(value<Id>(request, 'workflowId'), executionId, hash);
|
|
1441
|
+
}
|
|
1442
|
+
if (value<string>(review, 'postStatus') === 'posted') {
|
|
1443
|
+
const noteId = value<Id | null>(review, 'postedNoteId');
|
|
1444
|
+
if (noteId == null) reviewConflict('Review publication receipt is unavailable');
|
|
1445
|
+
return { status: 'posted', postedNoteId: String(noteId), canResend: false };
|
|
1446
|
+
}
|
|
1447
|
+
const requestId = value<Id>(request, 'id');
|
|
1448
|
+
const inboxId = value<Id>(inbox, 'id');
|
|
1449
|
+
const token = randomUUID();
|
|
1450
|
+
let ownClaim = false;
|
|
1451
|
+
let acquiredProject = false;
|
|
1452
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1453
|
+
const lockedRequest = await db
|
|
1454
|
+
.getCollection('gitReviewRequests')
|
|
1455
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1456
|
+
const lockedExecution = await db
|
|
1457
|
+
.getCollection('executions')
|
|
1458
|
+
.model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1459
|
+
const lockedInbox = await db
|
|
1460
|
+
.getCollection('gitReviewInbox')
|
|
1461
|
+
.model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1462
|
+
const lockedProject = await db.getCollection('gitReviewProjects').model.findOne({
|
|
1463
|
+
where: { projectKey: payload.source.projectKey },
|
|
1464
|
+
transaction,
|
|
1465
|
+
lock: transaction.LOCK.UPDATE,
|
|
1466
|
+
});
|
|
1467
|
+
const lockedReview = await db
|
|
1468
|
+
.getCollection('gitCodeReviews')
|
|
1469
|
+
.model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1470
|
+
if (
|
|
1471
|
+
!lockedRequest ||
|
|
1472
|
+
value<boolean>(lockedRequest, 'fenced') ||
|
|
1473
|
+
!value<boolean>(lockedRequest, 'aiSettled') ||
|
|
1474
|
+
String(value<Id>(lockedRequest, 'executionId')) !== String(executionId) ||
|
|
1475
|
+
value<string>(lockedRequest, 'resultFingerprint') !== hash
|
|
1476
|
+
)
|
|
1477
|
+
reviewConflict('Review is no longer available');
|
|
1478
|
+
if (
|
|
1479
|
+
!lockedExecution ||
|
|
1480
|
+
typeof value<unknown>(lockedExecution, 'status') !== 'number' ||
|
|
1481
|
+
value<number>(lockedExecution, 'status') === 0
|
|
1482
|
+
)
|
|
1483
|
+
reviewConflict('Review execution is not terminal');
|
|
1484
|
+
if (
|
|
1485
|
+
!lockedInbox ||
|
|
1486
|
+
!lockedProject ||
|
|
1487
|
+
!lockedReview ||
|
|
1488
|
+
fingerprint(value<string>(lockedReview, 'reviewMarkdown') || '') !== hash ||
|
|
1489
|
+
!['posting', 'post_unknown', 'post_failed', 'retrying'].includes(value<string>(lockedReview, 'postStatus'))
|
|
1490
|
+
)
|
|
1491
|
+
reviewConflict('Review publication cannot be retried');
|
|
1492
|
+
const active = value<Id | null>(lockedProject, 'activeInboxId');
|
|
1493
|
+
if (value<Id | null>(lockedProject, 'legacyPostReviewId') != null)
|
|
1494
|
+
reviewConflict('Another review is active for this project');
|
|
1495
|
+
if (active != null && String(active) !== String(inboxId))
|
|
1496
|
+
reviewConflict('Another review is active for this project');
|
|
1497
|
+
const existingClaim = value<string | null>(lockedRequest, 'postClaim');
|
|
1498
|
+
if (existingClaim) {
|
|
1499
|
+
if (allowResend) reviewConflict('A publication attempt may still be running');
|
|
1500
|
+
return;
|
|
1501
|
+
}
|
|
1502
|
+
if (active == null) {
|
|
1503
|
+
const [reserved] = await db.getCollection('gitReviewProjects').model.update(
|
|
1504
|
+
{ activeInboxId: inboxId },
|
|
1505
|
+
{
|
|
1506
|
+
where: { projectKey: payload.source.projectKey, activeInboxId: null, legacyPostReviewId: null },
|
|
1507
|
+
transaction,
|
|
1508
|
+
},
|
|
1509
|
+
);
|
|
1510
|
+
if (reserved !== 1) reviewConflict('Another review is active for this project');
|
|
1511
|
+
acquiredProject = true;
|
|
1512
|
+
}
|
|
1513
|
+
await lockedRequest.update({ postClaim: token, postClaimedAt: new Date() }, { transaction });
|
|
1514
|
+
ownClaim = true;
|
|
1515
|
+
});
|
|
1516
|
+
let sent = false;
|
|
1517
|
+
try {
|
|
1518
|
+
const repo = await db.getRepository('gitRepositories').findOne({ filterByTk: repositoryId });
|
|
1519
|
+
if (!repo) reviewConflict('Repository not found');
|
|
1520
|
+
const marker = `<!-- git-review:${String(requestId)}:${hash} -->`;
|
|
1521
|
+
let noteId = await findPublishedReview(db, repo, payload.source, markdown, marker);
|
|
1522
|
+
if (!noteId && allowResend) {
|
|
1523
|
+
if (!ownClaim) reviewConflict('A publication attempt may still be running');
|
|
1524
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1525
|
+
const current = await db
|
|
1526
|
+
.getCollection('gitReviewRequests')
|
|
1527
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1528
|
+
const project = await db.getCollection('gitReviewProjects').model.findOne({
|
|
1529
|
+
where: { projectKey: payload.source.projectKey },
|
|
1530
|
+
transaction,
|
|
1531
|
+
lock: transaction.LOCK.UPDATE,
|
|
1532
|
+
});
|
|
1533
|
+
if (
|
|
1534
|
+
!current ||
|
|
1535
|
+
value<boolean>(current, 'fenced') ||
|
|
1536
|
+
value<string | null>(current, 'postClaim') !== token ||
|
|
1537
|
+
!project ||
|
|
1538
|
+
String(value<Id | null>(project, 'activeInboxId')) !== String(inboxId)
|
|
1539
|
+
)
|
|
1540
|
+
reviewConflict('Review publication claim changed');
|
|
1541
|
+
const [changed] = await db
|
|
1542
|
+
.getCollection('gitCodeReviews')
|
|
1543
|
+
.model.update(
|
|
1544
|
+
{ postStatus: 'retrying' },
|
|
1545
|
+
{ where: { id: reviewId, postStatus: ['posting', 'post_unknown', 'post_failed'] }, transaction },
|
|
1546
|
+
);
|
|
1547
|
+
if (changed !== 1) reviewConflict('Review publication state changed');
|
|
1548
|
+
});
|
|
1549
|
+
sent = true;
|
|
1550
|
+
noteId = await publishPinnedReview(db, repo, payload.source, markdown, marker, async (start) => {
|
|
1551
|
+
const latestRoles = await resolveBackgroundReviewRoles(db, actor);
|
|
1552
|
+
if (
|
|
1553
|
+
roles.some((role) => !latestRoles.includes(role)) ||
|
|
1554
|
+
!(await hasRepositoryAccess({ acl: this.app.acl, roles, repositoryId, action: 'reviewWorkflowRetryPost' }))
|
|
1555
|
+
)
|
|
1556
|
+
reviewConflict('Permission denied');
|
|
1557
|
+
return this.startPublication(requestId, executionId, inboxId, reviewId, payload, hash, token, 'retry', start);
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
if (!noteId) return { status: 'unknown', canResend: ownClaim };
|
|
1561
|
+
if (!ownClaim) return { status: 'observed', postedNoteId: noteId, canResend: false };
|
|
1562
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1563
|
+
const lockedRequest = await db
|
|
1564
|
+
.getCollection('gitReviewRequests')
|
|
1565
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1566
|
+
const lockedInbox = await db
|
|
1567
|
+
.getCollection('gitReviewInbox')
|
|
1568
|
+
.model.findOne({ where: { id: inboxId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1569
|
+
const lockedProject = await db.getCollection('gitReviewProjects').model.findOne({
|
|
1570
|
+
where: { projectKey: payload.source.projectKey },
|
|
1571
|
+
transaction,
|
|
1572
|
+
lock: transaction.LOCK.UPDATE,
|
|
1573
|
+
});
|
|
1574
|
+
const lockedReview = await db
|
|
1575
|
+
.getCollection('gitCodeReviews')
|
|
1576
|
+
.model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1577
|
+
if (
|
|
1578
|
+
!lockedRequest ||
|
|
1579
|
+
value<boolean>(lockedRequest, 'fenced') ||
|
|
1580
|
+
value<string | null>(lockedRequest, 'postClaim') !== token ||
|
|
1581
|
+
value<string>(lockedRequest, 'resultFingerprint') !== hash ||
|
|
1582
|
+
!lockedInbox ||
|
|
1583
|
+
!lockedProject ||
|
|
1584
|
+
String(value<Id | null>(lockedProject, 'activeInboxId')) !== String(inboxId) ||
|
|
1585
|
+
!lockedReview ||
|
|
1586
|
+
fingerprint(value<string>(lockedReview, 'reviewMarkdown') || '') !== hash
|
|
1587
|
+
)
|
|
1588
|
+
reviewConflict('Review publication claim changed');
|
|
1589
|
+
if (
|
|
1590
|
+
value<string>(lockedReview, 'postStatus') === 'posted' &&
|
|
1591
|
+
String(value<Id>(lockedReview, 'postedNoteId')) !== String(noteId)
|
|
1592
|
+
)
|
|
1593
|
+
reviewConflict('Review publication state changed');
|
|
1594
|
+
const [cleared] = await db
|
|
1595
|
+
.getCollection('gitReviewRequests')
|
|
1596
|
+
.model.update(
|
|
1597
|
+
{ postClaim: null, postClaimedAt: null },
|
|
1598
|
+
{ where: { id: requestId, postClaim: token, fenced: false }, transaction },
|
|
1599
|
+
);
|
|
1600
|
+
if (cleared !== 1) reviewConflict('Review publication claim changed');
|
|
1601
|
+
await db.getRepository('gitCodeReviews').update({
|
|
1602
|
+
filterByTk: reviewId,
|
|
1603
|
+
values: { postStatus: 'posted', postedNoteId: noteId, error: null, status: 'completed' },
|
|
1604
|
+
transaction,
|
|
1605
|
+
});
|
|
1606
|
+
await db
|
|
1607
|
+
.getRepository('gitReviewInbox')
|
|
1608
|
+
.update({ filterByTk: inboxId, values: { state: 'completed' }, transaction });
|
|
1609
|
+
const [released] = await db
|
|
1610
|
+
.getCollection('gitReviewProjects')
|
|
1611
|
+
.model.update(
|
|
1612
|
+
{ activeInboxId: null },
|
|
1613
|
+
{ where: { projectKey: payload.source.projectKey, activeInboxId: inboxId }, transaction },
|
|
1614
|
+
);
|
|
1615
|
+
if (released !== 1) reviewConflict('Review project reservation changed');
|
|
1616
|
+
});
|
|
1617
|
+
ownClaim = false;
|
|
1618
|
+
acquiredProject = false;
|
|
1619
|
+
await this.reconcile().catch((error) => this.app.log?.error?.('Git review dispatch will be retried', error));
|
|
1620
|
+
return { status: 'posted', postedNoteId: noteId, canResend: false };
|
|
1621
|
+
} catch (error) {
|
|
1622
|
+
if (sent) {
|
|
1623
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1624
|
+
const current = await db
|
|
1625
|
+
.getCollection('gitReviewRequests')
|
|
1626
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1627
|
+
if (!current || value<boolean>(current, 'fenced') || value<string | null>(current, 'postClaim') !== token)
|
|
1628
|
+
return;
|
|
1629
|
+
const [changed] = await db
|
|
1630
|
+
.getCollection('gitCodeReviews')
|
|
1631
|
+
.model.update(
|
|
1632
|
+
{ postStatus: 'post_unknown', error: 'Review publication outcome is unknown' },
|
|
1633
|
+
{ where: { id: reviewId, postStatus: 'retrying' }, transaction },
|
|
1634
|
+
);
|
|
1635
|
+
if (changed)
|
|
1636
|
+
await db
|
|
1637
|
+
.getRepository('gitReviewInbox')
|
|
1638
|
+
.update({ filterByTk: inboxId, values: { state: 'quarantined' }, transaction });
|
|
1639
|
+
});
|
|
1640
|
+
acquiredProject = false;
|
|
1641
|
+
ownClaim = false;
|
|
1642
|
+
}
|
|
1643
|
+
throw error;
|
|
1644
|
+
} finally {
|
|
1645
|
+
// A failed status write does not prove that a started outbound request stopped.
|
|
1646
|
+
if (!sent && (ownClaim || acquiredProject)) {
|
|
1647
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1648
|
+
const current = await db
|
|
1649
|
+
.getCollection('gitReviewRequests')
|
|
1650
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1651
|
+
if (!current || value<string | null>(current, 'postClaim') !== token) return;
|
|
1652
|
+
await current.update({ postClaim: null, postClaimedAt: null }, { transaction });
|
|
1653
|
+
if (acquiredProject)
|
|
1654
|
+
await db
|
|
1655
|
+
.getCollection('gitReviewProjects')
|
|
1656
|
+
.model.update(
|
|
1657
|
+
{ activeInboxId: null },
|
|
1658
|
+
{ where: { projectKey: payload.source.projectKey, activeInboxId: inboxId }, transaction },
|
|
1659
|
+
);
|
|
1660
|
+
});
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
async resetPostClaim(reviewId: Id, actor: Id, expectedAttempt: string | null): Promise<void> {
|
|
1666
|
+
const db = this.app.db;
|
|
1667
|
+
const inbox = await db.getRepository('gitReviewInbox').findOne({ filter: { reviewId } });
|
|
1668
|
+
const request =
|
|
1669
|
+
inbox && (await db.getRepository('gitReviewRequests').findOne({ filter: { inboxId: value<Id>(inbox, 'id') } }));
|
|
1670
|
+
if (!inbox || !request) reviewConflict('Review request not found');
|
|
1671
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1672
|
+
const requestId = value<Id>(request, 'id');
|
|
1673
|
+
const locked = await db
|
|
1674
|
+
.getCollection('gitReviewRequests')
|
|
1675
|
+
.model.findOne({ where: { id: requestId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1676
|
+
if (!locked || value<boolean>(locked, 'fenced') || !value<boolean>(locked, 'aiSettled'))
|
|
1677
|
+
reviewConflict('No recoverable publication claim');
|
|
1678
|
+
const claim = value<string | null>(locked, 'postClaim') ?? null;
|
|
1679
|
+
if (claim !== expectedAttempt) reviewConflict('Review publication claim changed');
|
|
1680
|
+
const executionId = value<Id | null>(locked, 'executionId');
|
|
1681
|
+
const execution =
|
|
1682
|
+
executionId == null
|
|
1683
|
+
? null
|
|
1684
|
+
: await db
|
|
1685
|
+
.getCollection('executions')
|
|
1686
|
+
.model.findOne({ where: { id: executionId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1687
|
+
if (
|
|
1688
|
+
!execution ||
|
|
1689
|
+
typeof value<unknown>(execution, 'status') !== 'number' ||
|
|
1690
|
+
value<number>(execution, 'status') === 0
|
|
1691
|
+
)
|
|
1692
|
+
reviewConflict('Review execution is not terminal');
|
|
1693
|
+
const lockedInbox = await db
|
|
1694
|
+
.getCollection('gitReviewInbox')
|
|
1695
|
+
.model.findOne({ where: { id: value<Id>(inbox, 'id') }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1696
|
+
const project =
|
|
1697
|
+
lockedInbox &&
|
|
1698
|
+
(await db.getCollection('gitReviewProjects').model.findOne({
|
|
1699
|
+
where: { projectKey: value<string>(lockedInbox, 'projectKey') },
|
|
1700
|
+
transaction,
|
|
1701
|
+
lock: transaction.LOCK.UPDATE,
|
|
1702
|
+
}));
|
|
1703
|
+
const lockedReview = await db
|
|
1704
|
+
.getCollection('gitCodeReviews')
|
|
1705
|
+
.model.findOne({ where: { id: reviewId }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1706
|
+
if (
|
|
1707
|
+
!lockedInbox ||
|
|
1708
|
+
!lockedReview ||
|
|
1709
|
+
!['posting', 'post_unknown', 'post_failed', 'retrying'].includes(value<string>(lockedReview, 'postStatus'))
|
|
1710
|
+
)
|
|
1711
|
+
reviewConflict('Review publication cannot be recovered');
|
|
1712
|
+
const [reset] = await db
|
|
1713
|
+
.getCollection('gitReviewRequests')
|
|
1714
|
+
.model.update(
|
|
1715
|
+
{ postClaim: null, postClaimedAt: null, postResetBy: String(actor), postResetAt: new Date() },
|
|
1716
|
+
{ where: { id: requestId, postClaim: claim, fenced: false }, transaction },
|
|
1717
|
+
);
|
|
1718
|
+
if (reset !== 1) reviewConflict('Review publication claim changed');
|
|
1719
|
+
await lockedReview.update({ postStatus: 'post_unknown' }, { transaction });
|
|
1720
|
+
if (project)
|
|
1721
|
+
await db.getCollection('gitReviewProjects').model.update(
|
|
1722
|
+
{ activeInboxId: null },
|
|
1723
|
+
{
|
|
1724
|
+
where: {
|
|
1725
|
+
projectKey: value<string>(lockedInbox, 'projectKey'),
|
|
1726
|
+
activeInboxId: value<Id>(lockedInbox, 'id'),
|
|
1727
|
+
},
|
|
1728
|
+
transaction,
|
|
1729
|
+
},
|
|
1730
|
+
);
|
|
1731
|
+
await lockedInbox.update({ state: 'completed' }, { transaction });
|
|
1732
|
+
});
|
|
1733
|
+
await this.reconcile().catch((error) => this.app.log?.error?.('Git review dispatch will be retried', error));
|
|
1734
|
+
}
|
|
1735
|
+
|
|
1736
|
+
async markAISettled(requestId: Id, executionId: Id): Promise<void> {
|
|
1737
|
+
await this.owned(requestId, executionId);
|
|
1738
|
+
const integration = (this.app.pm.get('plugin-workflow-git-review') ||
|
|
1739
|
+
this.app.pm.get('workflow-git-review')) as unknown as
|
|
1740
|
+
| {
|
|
1741
|
+
assertAISettled?: (requestId: Id, executionId: Id) => Promise<void>;
|
|
1742
|
+
}
|
|
1743
|
+
| undefined;
|
|
1744
|
+
if (!integration?.assertAISettled) throw new Error('Review settlement verifier is unavailable');
|
|
1745
|
+
await integration.assertAISettled(requestId, executionId);
|
|
1746
|
+
const [updated] = await this.app.db
|
|
1747
|
+
.getCollection('gitReviewRequests')
|
|
1748
|
+
.model.update({ aiSettled: true }, { where: { id: requestId, executionId, aiSettled: false, fenced: false } });
|
|
1749
|
+
if (!updated) {
|
|
1750
|
+
const request = await this.app.db.getRepository('gitReviewRequests').findOne({ filterByTk: requestId });
|
|
1751
|
+
if (
|
|
1752
|
+
!request ||
|
|
1753
|
+
String(value<Id>(request, 'executionId')) !== String(executionId) ||
|
|
1754
|
+
value<boolean>(request, 'fenced') ||
|
|
1755
|
+
!value<boolean>(request, 'aiSettled')
|
|
1756
|
+
) {
|
|
1757
|
+
throw new Error('Review settlement could not be recorded');
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
|
|
1762
|
+
async onExecutionStatus(executionId: Id, status: number | string): Promise<void> {
|
|
1763
|
+
const db = this.app.db;
|
|
1764
|
+
const request = await db.getRepository('gitReviewRequests').findOne({ filter: { executionId } });
|
|
1765
|
+
if (!request || value<boolean>(request, 'fenced')) return;
|
|
1766
|
+
const execution = await db.getRepository('executions').findOne({ filterByTk: executionId });
|
|
1767
|
+
if (!execution || String(value<unknown>(execution, 'status')) !== String(status)) return;
|
|
1768
|
+
const inbox = await db.getRepository('gitReviewInbox').findOne({ filterByTk: value<Id>(request, 'inboxId') });
|
|
1769
|
+
if (!inbox || !['running', 'dispatched', 'quarantined'].includes(value<string>(inbox, 'state'))) return;
|
|
1770
|
+
if (value<string | null>(request, 'postClaim')) return;
|
|
1771
|
+
const review = await db.getRepository('gitCodeReviews').findOne({ filterByTk: value<Id>(request, 'reviewId') });
|
|
1772
|
+
let rejected = false;
|
|
1773
|
+
let settledFailure = false;
|
|
1774
|
+
const fingerprint = value<string | null>(request, 'resultFingerprint');
|
|
1775
|
+
if (Number(status) === -5 && value<boolean>(request, 'aiSettled') && fingerprint && review) {
|
|
1776
|
+
const integration = (this.app.pm.get('plugin-workflow-git-review') ||
|
|
1777
|
+
this.app.pm.get('workflow-git-review')) as unknown as
|
|
1778
|
+
| {
|
|
1779
|
+
assertManualRejection?: (workflowId: Id, executionId: Id, fingerprint: string) => Promise<void>;
|
|
1780
|
+
}
|
|
1781
|
+
| undefined;
|
|
1782
|
+
if (integration?.assertManualRejection) {
|
|
1783
|
+
try {
|
|
1784
|
+
await integration.assertManualRejection(value<Id>(request, 'workflowId'), executionId, fingerprint);
|
|
1785
|
+
rejected = true;
|
|
1786
|
+
} catch (_error) {
|
|
1787
|
+
rejected = false;
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
}
|
|
1791
|
+
if ([-1, -2].includes(Number(status))) {
|
|
1792
|
+
const integration = (this.app.pm.get('plugin-workflow-git-review') ||
|
|
1793
|
+
this.app.pm.get('workflow-git-review')) as unknown as
|
|
1794
|
+
| {
|
|
1795
|
+
assertNoInFlightAI?: (requestId: Id, executionId: Id) => Promise<void>;
|
|
1796
|
+
}
|
|
1797
|
+
| undefined;
|
|
1798
|
+
if (integration?.assertNoInFlightAI) {
|
|
1799
|
+
try {
|
|
1800
|
+
await integration.assertNoInFlightAI(value<Id>(request, 'id'), executionId);
|
|
1801
|
+
settledFailure = true;
|
|
1802
|
+
} catch (_error) {
|
|
1803
|
+
settledFailure = false;
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
const completed =
|
|
1808
|
+
Number(status) === 1 && review && ['posted', 'skipped'].includes(value<string>(review, 'postStatus'));
|
|
1809
|
+
const postUnresolved =
|
|
1810
|
+
review && ['posting', 'post_unknown', 'post_failed', 'retrying'].includes(value<string>(review, 'postStatus'));
|
|
1811
|
+
if (
|
|
1812
|
+
postUnresolved ||
|
|
1813
|
+
(!completed && !rejected && !settledFailure) ||
|
|
1814
|
+
(!settledFailure && (!value<boolean>(request, 'aiSettled') || !fingerprint)) ||
|
|
1815
|
+
!review
|
|
1816
|
+
) {
|
|
1817
|
+
if (Number(status) !== 0) {
|
|
1818
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1819
|
+
const current = await db
|
|
1820
|
+
.getCollection('gitReviewRequests')
|
|
1821
|
+
.model.findOne({ where: { id: value<Id>(request, 'id') }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1822
|
+
if (!current || value<boolean>(current, 'fenced') || value<string | null>(current, 'postClaim')) return;
|
|
1823
|
+
const [changed] = await db
|
|
1824
|
+
.getCollection('gitReviewInbox')
|
|
1825
|
+
.model.update(
|
|
1826
|
+
{ state: 'quarantined' },
|
|
1827
|
+
{ where: { id: value<Id>(inbox, 'id'), state: ['dispatched', 'running'] }, transaction },
|
|
1828
|
+
);
|
|
1829
|
+
if (changed === 1)
|
|
1830
|
+
await db.getRepository('gitCodeReviews').update({
|
|
1831
|
+
filterByTk: value<Id>(request, 'reviewId'),
|
|
1832
|
+
values: {
|
|
1833
|
+
status: 'failed',
|
|
1834
|
+
error: 'Workflow ended without confirmed AI settlement; project remains reserved',
|
|
1835
|
+
},
|
|
1836
|
+
transaction,
|
|
1837
|
+
});
|
|
1838
|
+
});
|
|
1839
|
+
}
|
|
1840
|
+
return;
|
|
1841
|
+
}
|
|
1842
|
+
await db.sequelize.transaction(async (transaction) => {
|
|
1843
|
+
const lockedRequest = await db.getCollection('gitReviewRequests').model.findOne({
|
|
1844
|
+
where: { id: value<Id>(request, 'id') },
|
|
1845
|
+
transaction,
|
|
1846
|
+
lock: transaction.LOCK.UPDATE,
|
|
1847
|
+
});
|
|
1848
|
+
if (
|
|
1849
|
+
!lockedRequest ||
|
|
1850
|
+
value<boolean>(lockedRequest, 'fenced') ||
|
|
1851
|
+
value<string | null>(lockedRequest, 'postClaim') ||
|
|
1852
|
+
(!settledFailure && !value<boolean>(lockedRequest, 'aiSettled'))
|
|
1853
|
+
)
|
|
1854
|
+
return;
|
|
1855
|
+
const lockedInbox = await db.getCollection('gitReviewInbox').model.findOne({
|
|
1856
|
+
where: { id: value<Id>(inbox, 'id') },
|
|
1857
|
+
transaction,
|
|
1858
|
+
lock: transaction.LOCK.UPDATE,
|
|
1859
|
+
});
|
|
1860
|
+
if (!lockedInbox || !['running', 'dispatched', 'quarantined'].includes(value<string>(lockedInbox, 'state')))
|
|
1861
|
+
return;
|
|
1862
|
+
const lockedReview = await db
|
|
1863
|
+
.getCollection('gitCodeReviews')
|
|
1864
|
+
.model.findOne({ where: { id: value<Id>(request, 'reviewId') }, transaction, lock: transaction.LOCK.UPDATE });
|
|
1865
|
+
if (
|
|
1866
|
+
!lockedReview ||
|
|
1867
|
+
['posting', 'post_unknown', 'post_failed', 'retrying'].includes(value<string>(lockedReview, 'postStatus'))
|
|
1868
|
+
)
|
|
1869
|
+
return;
|
|
1870
|
+
const [released] = await db.getCollection('gitReviewProjects').model.update(
|
|
1871
|
+
{ activeInboxId: null },
|
|
1872
|
+
{
|
|
1873
|
+
where: { projectKey: value<string>(inbox, 'projectKey'), activeInboxId: value<Id>(inbox, 'id') },
|
|
1874
|
+
transaction,
|
|
1875
|
+
},
|
|
1876
|
+
);
|
|
1877
|
+
if (released !== 1) return;
|
|
1878
|
+
if (settledFailure) {
|
|
1879
|
+
await lockedRequest.update({ aiSettled: true }, { transaction });
|
|
1880
|
+
await db.getRepository('gitCodeReviews').update({
|
|
1881
|
+
filterByTk: value<Id>(request, 'reviewId'),
|
|
1882
|
+
values: { status: 'failed', error: 'Workflow failed after all started LLM calls settled' },
|
|
1883
|
+
transaction,
|
|
1884
|
+
});
|
|
1885
|
+
}
|
|
1886
|
+
if (rejected) {
|
|
1887
|
+
await db.getRepository('gitCodeReviews').update({
|
|
1888
|
+
filterByTk: value<Id>(request, 'reviewId'),
|
|
1889
|
+
values: { postStatus: 'rejected', status: 'completed' },
|
|
1890
|
+
transaction,
|
|
1891
|
+
});
|
|
1892
|
+
}
|
|
1893
|
+
await db
|
|
1894
|
+
.getRepository('gitReviewInbox')
|
|
1895
|
+
.update({ filterByTk: value<Id>(inbox, 'id'), values: { state: 'completed' }, transaction });
|
|
1896
|
+
});
|
|
1897
|
+
await this.reconcile();
|
|
1898
|
+
}
|
|
1899
|
+
}
|