@leitwerk-dev/gitlab 0.3.0 → 0.4.0
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 +154 -1
- package/dist/capability.d.ts +3 -0
- package/dist/capability.d.ts.map +1 -1
- package/dist/chunk-YPCOVBQS.js +2343 -0
- package/dist/chunk-YPCOVBQS.js.map +1 -0
- package/dist/client.d.ts +99 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/external.d.ts +24 -4
- package/dist/external.d.ts.map +1 -1
- package/dist/index.d.ts +8 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +512 -10
- package/dist/index.js.map +1 -1
- package/dist/issue-watcher.d.ts +2 -2
- package/dist/issue-watcher.d.ts.map +1 -1
- package/dist/launch.d.ts +40 -0
- package/dist/launch.d.ts.map +1 -0
- package/dist/maintenance-labels.d.ts +30 -0
- package/dist/maintenance-labels.d.ts.map +1 -0
- package/dist/maintenance.d.ts +132 -0
- package/dist/maintenance.d.ts.map +1 -0
- package/dist/publication-maintenance.d.ts +7 -0
- package/dist/publication-maintenance.d.ts.map +1 -0
- package/dist/publication.d.ts +37 -0
- package/dist/publication.d.ts.map +1 -0
- package/dist/repository-catalog.d.ts +16 -0
- package/dist/repository-catalog.d.ts.map +1 -0
- package/dist/setup.d.ts +8 -2
- package/dist/setup.d.ts.map +1 -1
- package/dist/testing.d.ts +10 -1
- package/dist/testing.d.ts.map +1 -1
- package/dist/testing.js +125 -5
- package/dist/testing.js.map +1 -1
- package/dist/ticket-creation.d.ts +5 -0
- package/dist/ticket-creation.d.ts.map +1 -0
- package/dist/tools.d.ts +100 -3
- package/dist/tools.d.ts.map +1 -1
- package/package.json +7 -7
- package/src/capability.ts +3 -0
- package/src/client.ts +275 -12
- package/src/delivery-tools.ts +4 -4
- package/src/external.ts +91 -24
- package/src/index.ts +58 -10
- package/src/issue-watcher.ts +16 -14
- package/src/launch.ts +63 -0
- package/src/maintenance-labels.ts +129 -0
- package/src/maintenance.ts +759 -0
- package/src/publication-maintenance.ts +288 -0
- package/src/publication.ts +234 -0
- package/src/repository-catalog.ts +94 -0
- package/src/setup.ts +115 -6
- package/src/testing.ts +143 -4
- package/src/ticket-creation.ts +145 -0
- package/src/tools.ts +382 -26
- package/dist/chunk-H4JCQNDY.js +0 -1162
- package/dist/chunk-H4JCQNDY.js.map +0 -1
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
import { asUnknownRecord, type ProcessInstance, type ProcessProject } from "@leitwerk-dev/domain";
|
|
2
|
+
import type { ExternalWrites } from "@leitwerk-dev/external-writes";
|
|
3
|
+
import {
|
|
4
|
+
bindExternalWrites,
|
|
5
|
+
type ExternalWriteLogRepoLike,
|
|
6
|
+
} from "@leitwerk-dev/external-writes/internal";
|
|
7
|
+
import {
|
|
8
|
+
type Codec,
|
|
9
|
+
type CoreServerSetupDeps,
|
|
10
|
+
createCapabilityToken,
|
|
11
|
+
type ExternalActionSource,
|
|
12
|
+
type ProcessObservationUpdate,
|
|
13
|
+
type ServerExtensionAPI,
|
|
14
|
+
} from "@leitwerk-dev/process-sdk";
|
|
15
|
+
import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
|
|
16
|
+
import type { GitLabIntegration } from "./capability.js";
|
|
17
|
+
import { type GitLabFeedback, type GitLabObservation, observeMergeRequest } from "./client.js";
|
|
18
|
+
import {
|
|
19
|
+
type GitLabDeliveryObservation,
|
|
20
|
+
gitLabFeedbackReadyAt,
|
|
21
|
+
observationKey,
|
|
22
|
+
pendingGitLabFeedback,
|
|
23
|
+
} from "./external.js";
|
|
24
|
+
import {
|
|
25
|
+
ensureGitLabMaintenanceLabels,
|
|
26
|
+
GITLAB_ACTIVE_LABEL,
|
|
27
|
+
gitLabActivationStatus,
|
|
28
|
+
readGitLabLabels,
|
|
29
|
+
readMaintainedGitLabLabels,
|
|
30
|
+
} from "./maintenance-labels.js";
|
|
31
|
+
import { ensureGitLabComment, ensureGitLabSeenReaction, resolveGitLabBinding } from "./tools.js";
|
|
32
|
+
|
|
33
|
+
/** @public */
|
|
34
|
+
export const GITLAB_MAINTAINED_KIND = "@leitwerk-dev/gitlab.maintained";
|
|
35
|
+
/** Source for edges declared by a maintained process; no polling code belongs in the process. @public */
|
|
36
|
+
export function gitlabMaintenanceSource<P, S>(): ExternalActionSource<
|
|
37
|
+
P,
|
|
38
|
+
S,
|
|
39
|
+
GitLabMaintenanceEvent<S>
|
|
40
|
+
> {
|
|
41
|
+
return {
|
|
42
|
+
kind: GITLAB_MAINTAINED_KIND,
|
|
43
|
+
label: "GitLab MR maintenance",
|
|
44
|
+
config: {},
|
|
45
|
+
inputMode: "none",
|
|
46
|
+
resolve: ({ params, state, projects }) => ({ params, state, projects }),
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** @public */
|
|
50
|
+
export interface GitLabMaintenanceEvent<S> {
|
|
51
|
+
/** @public */
|
|
52
|
+
state: S;
|
|
53
|
+
}
|
|
54
|
+
/** @public */
|
|
55
|
+
export interface GitLabMaintenanceDestinations {
|
|
56
|
+
/** @public */
|
|
57
|
+
feedback: string;
|
|
58
|
+
/** @public */
|
|
59
|
+
conflict: string;
|
|
60
|
+
/** @public */
|
|
61
|
+
ci: string;
|
|
62
|
+
}
|
|
63
|
+
/** @public */
|
|
64
|
+
export interface GitLabMaintainedBinding {
|
|
65
|
+
/** Process repository key. @public */ projectKey: string;
|
|
66
|
+
/** @public */ profile: string;
|
|
67
|
+
/** @public */ projectId: number;
|
|
68
|
+
/** @public */ iid: number;
|
|
69
|
+
/** Pinned installation. @public */ origin?: string;
|
|
70
|
+
}
|
|
71
|
+
/** @public */
|
|
72
|
+
export interface GitLabMaintenanceSettings {
|
|
73
|
+
/** Consumed cursor; advance only after publication or a no-change result. @public */ cursor?: number;
|
|
74
|
+
/** @public */ since?: string;
|
|
75
|
+
/** @public */ quietPeriodMs?: number;
|
|
76
|
+
/** @public */ pollInterval?: string;
|
|
77
|
+
/** Original activation boundary, when adopting a receipt. @public */ activationAfter?: number;
|
|
78
|
+
/** Existing activation receipt key, retained on upgrade. @public */ activationWriteKey?: string;
|
|
79
|
+
}
|
|
80
|
+
/** @public */
|
|
81
|
+
export interface GitLabMaintenanceContext<P, S> {
|
|
82
|
+
/** @public */ readonly process: ProcessInstance;
|
|
83
|
+
/** @public */ readonly projects: readonly ProcessProject[];
|
|
84
|
+
/** @public */ readonly params: P;
|
|
85
|
+
/** @public */ readonly state: S;
|
|
86
|
+
/** @public */ readonly now: number;
|
|
87
|
+
/** @public */ readonly signal: AbortSignal;
|
|
88
|
+
/** @public */ readonly externalWrites: ExternalWrites;
|
|
89
|
+
/** Project-bound operations on the server, using the durable external-write log. @public */
|
|
90
|
+
callIntegrationTool(name: string, args: Record<string, unknown>): Promise<unknown>;
|
|
91
|
+
}
|
|
92
|
+
/** @public */
|
|
93
|
+
export interface GitLabMaintenanceDecision<S> {
|
|
94
|
+
/** @public */ state: S;
|
|
95
|
+
/** Destination key, or an additional recovery action declared by the process. @public */ action?: string;
|
|
96
|
+
/** Process-specific event fields supplied to its external edge. @public */ event?: Record<
|
|
97
|
+
string,
|
|
98
|
+
unknown
|
|
99
|
+
>;
|
|
100
|
+
}
|
|
101
|
+
/** @public */
|
|
102
|
+
export interface GitLabMaintenanceMessage {
|
|
103
|
+
/** @public */ writeKey: string;
|
|
104
|
+
/** @public */ body: string;
|
|
105
|
+
/** @public */ discussionId?: string;
|
|
106
|
+
}
|
|
107
|
+
/** @public */
|
|
108
|
+
export interface GitLabMaintainedProcess<
|
|
109
|
+
P,
|
|
110
|
+
S,
|
|
111
|
+
O extends GitLabObservation = GitLabDeliveryObservation,
|
|
112
|
+
> {
|
|
113
|
+
/** @public */ processId: string;
|
|
114
|
+
/** @public */ paramsCodec: Codec<P>;
|
|
115
|
+
/** @public */ stateCodec: Codec<S>;
|
|
116
|
+
/** External edge identities for business work. @public */ destinations: GitLabMaintenanceDestinations;
|
|
117
|
+
/** Defaults to gitlabMaintenanceSource. @public */ sourceKind?: string;
|
|
118
|
+
/** Defaults to each project's GitLab metadata. @public */ bindings?(
|
|
119
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
120
|
+
): readonly GitLabMaintainedBinding[];
|
|
121
|
+
/** @public */ settings?(
|
|
122
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
123
|
+
binding: GitLabMaintainedBinding,
|
|
124
|
+
): GitLabMaintenanceSettings;
|
|
125
|
+
/** Optional process-specific admission and diagnostic reads. @public */ assess?(
|
|
126
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
127
|
+
binding: GitLabMaintainedBinding,
|
|
128
|
+
): Promise<O>;
|
|
129
|
+
/** Process-specific routing/scope admission for work, reactions and replies. @public */
|
|
130
|
+
eligible?(
|
|
131
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
132
|
+
binding: GitLabMaintainedBinding,
|
|
133
|
+
observation: O,
|
|
134
|
+
): boolean;
|
|
135
|
+
/** Recheck process-specific write authorization before mutations. @public */
|
|
136
|
+
canWrite?(
|
|
137
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
138
|
+
binding: GitLabMaintainedBinding,
|
|
139
|
+
): Promise<boolean>;
|
|
140
|
+
/** Optional bounded infrastructure retry; repair budgets remain process policy. @public */
|
|
141
|
+
retry?: GitLabMaintenanceRetry;
|
|
142
|
+
/** Pure repair policy; shared maintenance supplies settled feedback and observations. @public */
|
|
143
|
+
observe(
|
|
144
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
145
|
+
binding: GitLabMaintainedBinding,
|
|
146
|
+
observation: O & GitLabDeliveryObservation,
|
|
147
|
+
): GitLabMaintenanceDecision<S>;
|
|
148
|
+
/** Persist a stopped binding in business results. @public */ stopped?(
|
|
149
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
150
|
+
binding: GitLabMaintainedBinding,
|
|
151
|
+
): S;
|
|
152
|
+
/** Persist merge/closure in business results. @public */ terminal?(
|
|
153
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
154
|
+
binding: GitLabMaintainedBinding,
|
|
155
|
+
observation: GitLabObservation,
|
|
156
|
+
): S;
|
|
157
|
+
/** Existing gated business position used when in-flight work is superseded. @public */ idleTurnId: string;
|
|
158
|
+
/** Binding for the selected repair or operator decision; unrelated idle work stays selected. @public */
|
|
159
|
+
currentBinding?(ctx: GitLabMaintenanceContext<P, S>): string | undefined;
|
|
160
|
+
/** Durable replies/exhaustion messages; mechanical delivery stays in the shared server. @public */ messages?(
|
|
161
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
162
|
+
binding: GitLabMaintainedBinding,
|
|
163
|
+
): readonly GitLabMaintenanceMessage[];
|
|
164
|
+
/** Clear an acknowledged no-change or published batch. Called only after all messages are durable. @public */ settled?(
|
|
165
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
166
|
+
binding: GitLabMaintainedBinding,
|
|
167
|
+
): S;
|
|
168
|
+
/** Optional cancellation of the source request, checked during running work and operator waits. @public */
|
|
169
|
+
cancelled?(ctx: GitLabMaintenanceContext<P, S>): Promise<boolean>;
|
|
170
|
+
/** Pure completion policy; ownership ends before remote completion writes. @public */
|
|
171
|
+
completion?(
|
|
172
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
173
|
+
records: Readonly<Record<string, GitLabMaintenanceRecord>>,
|
|
174
|
+
): "completed" | "aborted" | undefined;
|
|
175
|
+
/** Durable terminal writes; retried after completion without allocating a worker. @public */
|
|
176
|
+
complete?(
|
|
177
|
+
ctx: GitLabMaintenanceContext<P, S>,
|
|
178
|
+
records: Readonly<Record<string, GitLabMaintenanceRecord>>,
|
|
179
|
+
): Promise<void>;
|
|
180
|
+
}
|
|
181
|
+
/** @public */
|
|
182
|
+
export interface GitLabMaintenanceRetry {
|
|
183
|
+
/** Maximum automatic retries per failed business execution. @public */
|
|
184
|
+
maxAttempts: number;
|
|
185
|
+
}
|
|
186
|
+
/** Durable activation and observation, kept separately from worker-owned outcome snapshots. @public */
|
|
187
|
+
export interface GitLabMaintenanceRecord {
|
|
188
|
+
/** @public */ binding: GitLabMaintainedBinding;
|
|
189
|
+
/** @public */ after: number;
|
|
190
|
+
/** @public */ status: "active" | "stopped" | "merged" | "closed" | "deleted";
|
|
191
|
+
/** @public */ cursor: number;
|
|
192
|
+
/** @public */ pendingFeedback: GitLabFeedback[];
|
|
193
|
+
/** @public */ observation?: GitLabDeliveryObservation;
|
|
194
|
+
/** @public */ refreshError?: string;
|
|
195
|
+
}
|
|
196
|
+
/** @public */
|
|
197
|
+
export interface GitLabMaintenance {
|
|
198
|
+
/** @public */ register<P, S, O extends GitLabObservation>(
|
|
199
|
+
policy: GitLabMaintainedProcess<P, S, O>,
|
|
200
|
+
): void;
|
|
201
|
+
/** Recheck remote ownership immediately before publication, replies or reactions. @public */
|
|
202
|
+
assertOwnership(instanceId: string, projectKey: string, signal?: AbortSignal): Promise<void>;
|
|
203
|
+
/** @public */ ownsProcess(processId: string): boolean;
|
|
204
|
+
}
|
|
205
|
+
/** @public */
|
|
206
|
+
export const gitlabMaintenance = createCapabilityToken<GitLabMaintenance>(
|
|
207
|
+
"@leitwerk-dev/gitlab.maintenance",
|
|
208
|
+
);
|
|
209
|
+
/** Register a typed process policy through the existing capability registry. @public */
|
|
210
|
+
export function registerGitLabMaintainedProcess<P, S, O extends GitLabObservation>(
|
|
211
|
+
api: ServerExtensionAPI,
|
|
212
|
+
policy: GitLabMaintainedProcess<P, S, O>,
|
|
213
|
+
): void {
|
|
214
|
+
const service = api.require(gitlabMaintenance);
|
|
215
|
+
if (Array.isArray(service)) throw new Error("GitLab maintenance must be singular");
|
|
216
|
+
service.register(policy);
|
|
217
|
+
}
|
|
218
|
+
/** @internal */
|
|
219
|
+
export const maintenanceRecords = (
|
|
220
|
+
process: ProcessInstance,
|
|
221
|
+
): Record<string, GitLabMaintenanceRecord> =>
|
|
222
|
+
(asUnknownRecord(process.metadata?.gitlabMaintenance) ?? {}) as Record<
|
|
223
|
+
string,
|
|
224
|
+
GitLabMaintenanceRecord
|
|
225
|
+
>;
|
|
226
|
+
|
|
227
|
+
/** One server service owns all registered processes, including running work and operator waits. @internal */
|
|
228
|
+
export function createGitLabMaintenance(
|
|
229
|
+
api: ServerExtensionAPI,
|
|
230
|
+
deps: CoreServerSetupDeps,
|
|
231
|
+
integration: GitLabIntegration,
|
|
232
|
+
now: () => number = Date.now,
|
|
233
|
+
): GitLabMaintenance & {
|
|
234
|
+
/** @internal */
|
|
235
|
+
poll(): Promise<ReturnType<typeof emptyPollResult>>;
|
|
236
|
+
} {
|
|
237
|
+
const policies = new Map<string, GitLabMaintainedProcess<unknown, unknown>>();
|
|
238
|
+
const due = new Map<string, { at: number; failures: number; inputs: string }>();
|
|
239
|
+
const completionDue = new Map<string, { at: number; failures: number }>();
|
|
240
|
+
const workKey = (process: ProcessInstance) =>
|
|
241
|
+
JSON.stringify([
|
|
242
|
+
process.paramsJson,
|
|
243
|
+
process.stateJson,
|
|
244
|
+
process.planRevision,
|
|
245
|
+
process.selectedTurnId,
|
|
246
|
+
process.lifecycleStatus,
|
|
247
|
+
process.currentExecution,
|
|
248
|
+
]);
|
|
249
|
+
const repo = deps.externalWrites as ExternalWriteLogRepoLike;
|
|
250
|
+
const observe = (expected: ProcessInstance, update: Omit<ProcessObservationUpdate, "expected">) =>
|
|
251
|
+
deps.commands.applyProcessObservation(expected.id, { expected, ...update });
|
|
252
|
+
const context = (
|
|
253
|
+
process: ProcessInstance,
|
|
254
|
+
policy: GitLabMaintainedProcess<unknown, unknown>,
|
|
255
|
+
): GitLabMaintenanceContext<unknown, unknown> => ({
|
|
256
|
+
process,
|
|
257
|
+
projects: deps.projects.listByInstance(process.id),
|
|
258
|
+
params: policy.paramsCodec.parse(JSON.parse(process.paramsJson ?? "null")),
|
|
259
|
+
state: policy.stateCodec.parse(JSON.parse(process.stateJson ?? "null")),
|
|
260
|
+
now: now(),
|
|
261
|
+
signal: AbortSignal.timeout(30_000),
|
|
262
|
+
externalWrites: bindExternalWrites(repo, process.id),
|
|
263
|
+
callIntegrationTool: (name, args) => {
|
|
264
|
+
if (!deps.callIntegrationTool)
|
|
265
|
+
throw new Error("Server maintenance operations are unavailable");
|
|
266
|
+
return deps.callIntegrationTool(
|
|
267
|
+
process,
|
|
268
|
+
String(args.projectKey ?? "repo"),
|
|
269
|
+
name,
|
|
270
|
+
args,
|
|
271
|
+
AbortSignal.timeout(30_000),
|
|
272
|
+
);
|
|
273
|
+
},
|
|
274
|
+
});
|
|
275
|
+
const bindings = (
|
|
276
|
+
ctx: GitLabMaintenanceContext<unknown, unknown>,
|
|
277
|
+
policy: GitLabMaintainedProcess<unknown, unknown>,
|
|
278
|
+
) =>
|
|
279
|
+
policy.bindings?.(ctx) ??
|
|
280
|
+
ctx.projects.flatMap((project) => {
|
|
281
|
+
if (!asUnknownRecord(project.metadata?.gitlab)?.iid) return [];
|
|
282
|
+
return [
|
|
283
|
+
{
|
|
284
|
+
projectKey: project.key,
|
|
285
|
+
...resolveGitLabBinding({ process: ctx.process, project }, integration),
|
|
286
|
+
origin: asUnknownRecord(project.metadata?.gitlab)?.origin as string | undefined,
|
|
287
|
+
},
|
|
288
|
+
];
|
|
289
|
+
});
|
|
290
|
+
const completionStatus = (
|
|
291
|
+
ctx: GitLabMaintenanceContext<unknown, unknown>,
|
|
292
|
+
policy: GitLabMaintainedProcess<unknown, unknown>,
|
|
293
|
+
records: Record<string, GitLabMaintenanceRecord>,
|
|
294
|
+
) => {
|
|
295
|
+
if (Object.values(records).some((record) => record.status === "deleted"))
|
|
296
|
+
return "aborted" as const;
|
|
297
|
+
if (policy.completion) return policy.completion(ctx, records);
|
|
298
|
+
return bindings(ctx, policy).every(
|
|
299
|
+
(binding) => records[binding.projectKey] && records[binding.projectKey].status !== "active",
|
|
300
|
+
)
|
|
301
|
+
? Object.values(records).some((record) => record.status === "merged")
|
|
302
|
+
? ("completed" as const)
|
|
303
|
+
: ("aborted" as const)
|
|
304
|
+
: undefined;
|
|
305
|
+
};
|
|
306
|
+
const live = (process: ProcessInstance) =>
|
|
307
|
+
!["completed", "aborted"].includes(process.lifecycleStatus);
|
|
308
|
+
const unchangedWork = (fresh: ProcessInstance, expected: ProcessInstance) =>
|
|
309
|
+
workKey(fresh) === workKey(expected);
|
|
310
|
+
const same = (expected: ProcessInstance) => {
|
|
311
|
+
const fresh = deps.processes.getById(expected.id);
|
|
312
|
+
return (
|
|
313
|
+
!!fresh &&
|
|
314
|
+
unchangedWork(fresh, expected) &&
|
|
315
|
+
JSON.stringify(fresh.metadata?.gitlabMaintenance) ===
|
|
316
|
+
JSON.stringify(expected.metadata?.gitlabMaintenance)
|
|
317
|
+
);
|
|
318
|
+
};
|
|
319
|
+
const scheduleNext = (
|
|
320
|
+
key: string,
|
|
321
|
+
process: ProcessInstance,
|
|
322
|
+
settings: GitLabMaintenanceSettings,
|
|
323
|
+
) =>
|
|
324
|
+
due.set(key, {
|
|
325
|
+
at: now() + parseDurationMs(settings.pollInterval ?? "30s", 30_000),
|
|
326
|
+
failures: 0,
|
|
327
|
+
inputs: workKey(deps.processes.getById(process.id) ?? process),
|
|
328
|
+
});
|
|
329
|
+
const service: GitLabMaintenance = {
|
|
330
|
+
register(policy) {
|
|
331
|
+
if (
|
|
332
|
+
policy.retry &&
|
|
333
|
+
(!Number.isInteger(policy.retry.maxAttempts) || policy.retry.maxAttempts < 0)
|
|
334
|
+
)
|
|
335
|
+
throw new Error("GitLab maintenance retries must be a nonnegative integer");
|
|
336
|
+
if (policies.has(policy.processId))
|
|
337
|
+
throw new Error(`Duplicate GitLab maintenance policy '${policy.processId}'`);
|
|
338
|
+
policies.set(
|
|
339
|
+
policy.processId,
|
|
340
|
+
policy as unknown as GitLabMaintainedProcess<unknown, unknown>,
|
|
341
|
+
);
|
|
342
|
+
},
|
|
343
|
+
ownsProcess: (processId) => policies.has(processId),
|
|
344
|
+
async assertOwnership(instanceId, projectKey, signal) {
|
|
345
|
+
let process = deps.processes.getById(instanceId);
|
|
346
|
+
if (!process || !live(process)) throw new Error("GitLab maintenance ownership ended");
|
|
347
|
+
const policy = policies.get(process.processId);
|
|
348
|
+
if (!policy) return;
|
|
349
|
+
let ctx = context(process, policy);
|
|
350
|
+
const binding = bindings(ctx, policy).find((item) => item.projectKey === projectKey);
|
|
351
|
+
if (!binding) return; // Initial publication has not created its MR yet.
|
|
352
|
+
let record = maintenanceRecords(process)[projectKey];
|
|
353
|
+
if (record && record.status !== "active")
|
|
354
|
+
throw new Error("GitLab maintenance ownership ended");
|
|
355
|
+
const client = integration.client(binding.profile);
|
|
356
|
+
if (binding.origin && binding.origin !== client.baseUrl)
|
|
357
|
+
throw new Error("GitLab installation changed");
|
|
358
|
+
let labels = await readGitLabLabels(client, binding.projectId, binding.iid, signal);
|
|
359
|
+
const settings = policy.settings?.(ctx, binding) ?? {};
|
|
360
|
+
const activationKey =
|
|
361
|
+
settings.activationWriteKey ?? `gitlab:active:${process.id}:${projectKey}:${binding.iid}`;
|
|
362
|
+
if (!record) {
|
|
363
|
+
if (repo.hasDedupKey(activationKey) && !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL))
|
|
364
|
+
throw new Error("GitLab maintenance ownership ended");
|
|
365
|
+
record = {
|
|
366
|
+
binding,
|
|
367
|
+
after: settings.activationAfter ?? labels.events.at(-1)?.id ?? 0,
|
|
368
|
+
status: "active",
|
|
369
|
+
cursor: settings.cursor ?? 0,
|
|
370
|
+
pendingFeedback: [],
|
|
371
|
+
};
|
|
372
|
+
const saved = await observe(process, {
|
|
373
|
+
projectsJson: JSON.stringify(ctx.projects),
|
|
374
|
+
metadata: { gitlabMaintenance: { ...maintenanceRecords(process), [projectKey]: record } },
|
|
375
|
+
preserveUpdatedAt: true,
|
|
376
|
+
});
|
|
377
|
+
if (!saved.ok) throw new Error("GitLab maintenance ownership changed");
|
|
378
|
+
process = deps.processes.getById(instanceId);
|
|
379
|
+
if (!process || !live(process)) throw new Error("GitLab maintenance ownership ended");
|
|
380
|
+
const adopted = process;
|
|
381
|
+
await ensureGitLabMaintenanceLabels({
|
|
382
|
+
client,
|
|
383
|
+
writes: ctx.externalWrites,
|
|
384
|
+
projectId: binding.projectId,
|
|
385
|
+
iid: binding.iid,
|
|
386
|
+
after: record.after,
|
|
387
|
+
status: "active",
|
|
388
|
+
writeKey: activationKey,
|
|
389
|
+
guard: async () => same(adopted),
|
|
390
|
+
signal,
|
|
391
|
+
});
|
|
392
|
+
labels = await readGitLabLabels(client, binding.projectId, binding.iid, signal);
|
|
393
|
+
ctx = context(process, policy);
|
|
394
|
+
}
|
|
395
|
+
const after = record.after;
|
|
396
|
+
if (
|
|
397
|
+
!same(process) ||
|
|
398
|
+
labels.mr.state !== "opened" ||
|
|
399
|
+
gitLabActivationStatus(after, labels) === "removed" ||
|
|
400
|
+
!labels.mr.labels.includes(GITLAB_ACTIVE_LABEL)
|
|
401
|
+
)
|
|
402
|
+
throw new Error("GitLab maintenance ownership ended");
|
|
403
|
+
if (policy.canWrite && !(await policy.canWrite(ctx, binding)))
|
|
404
|
+
throw new Error("GitLab maintenance writes are suspended by process policy");
|
|
405
|
+
},
|
|
406
|
+
};
|
|
407
|
+
api.provide(gitlabMaintenance, service);
|
|
408
|
+
const polling = deps.polling.create({
|
|
409
|
+
id: "gitlab-maintenance",
|
|
410
|
+
pollInterval: () => "5s",
|
|
411
|
+
isEnabled: () => true,
|
|
412
|
+
defaultIntervalMs: 5000,
|
|
413
|
+
async pollOnce() {
|
|
414
|
+
const result = emptyPollResult();
|
|
415
|
+
for (const snapshot of deps.processes.listAll()) {
|
|
416
|
+
const policy = policies.get(snapshot.processId);
|
|
417
|
+
if (!policy) continue;
|
|
418
|
+
let ctx = context(snapshot, policy);
|
|
419
|
+
for (const binding of bindings(ctx, policy)) {
|
|
420
|
+
const key = `${snapshot.id}:${binding.projectKey}`;
|
|
421
|
+
const previous = due.get(key);
|
|
422
|
+
if (previous && previous.at > now() && previous.inputs === workKey(snapshot)) continue;
|
|
423
|
+
try {
|
|
424
|
+
const process = deps.processes.getById(snapshot.id);
|
|
425
|
+
if (!process) continue;
|
|
426
|
+
ctx = context(process, policy);
|
|
427
|
+
const settings = policy.settings?.(ctx, binding) ?? {};
|
|
428
|
+
const known = maintenanceRecords(process)[binding.projectKey];
|
|
429
|
+
if (known?.status === "deleted") continue;
|
|
430
|
+
if (
|
|
431
|
+
known &&
|
|
432
|
+
known.status !== "active" &&
|
|
433
|
+
process.metadata?.gitlabMaintenanceCompleted &&
|
|
434
|
+
repo.hasDedupKey(
|
|
435
|
+
`gitlab:${known.status}:${process.id}:${binding.projectKey}:${binding.iid}`,
|
|
436
|
+
)
|
|
437
|
+
)
|
|
438
|
+
continue;
|
|
439
|
+
const client = integration.client(binding.profile);
|
|
440
|
+
if (binding.origin && client.baseUrl !== binding.origin)
|
|
441
|
+
throw new Error("GitLab installation changed");
|
|
442
|
+
const labels = await readMaintainedGitLabLabels(
|
|
443
|
+
client,
|
|
444
|
+
binding.projectId,
|
|
445
|
+
binding.iid,
|
|
446
|
+
ctx.signal,
|
|
447
|
+
);
|
|
448
|
+
const records = structuredClone(maintenanceRecords(process));
|
|
449
|
+
let record = records[binding.projectKey];
|
|
450
|
+
if (record && JSON.stringify(record.binding) !== JSON.stringify(binding))
|
|
451
|
+
throw new Error("Maintained MR binding changed");
|
|
452
|
+
if (!record)
|
|
453
|
+
record = records[binding.projectKey] = {
|
|
454
|
+
binding,
|
|
455
|
+
after: settings.activationAfter ?? labels?.events.at(-1)?.id ?? 0,
|
|
456
|
+
status: "active",
|
|
457
|
+
cursor: settings.cursor ?? 0,
|
|
458
|
+
pendingFeedback: [],
|
|
459
|
+
};
|
|
460
|
+
record.cursor = Math.max(record.cursor, settings.cursor ?? 0);
|
|
461
|
+
const activationKey =
|
|
462
|
+
settings.activationWriteKey ??
|
|
463
|
+
`gitlab:active:${process.id}:${binding.projectKey}:${binding.iid}`;
|
|
464
|
+
let stopped = false;
|
|
465
|
+
let state = ctx.state;
|
|
466
|
+
if (!labels) {
|
|
467
|
+
record.status = "deleted";
|
|
468
|
+
record.pendingFeedback = [];
|
|
469
|
+
delete record.observation;
|
|
470
|
+
state = policy.stopped?.(ctx, binding) ?? state;
|
|
471
|
+
stopped = true;
|
|
472
|
+
} else if (record.status === "active") {
|
|
473
|
+
if (labels.mr.state !== "opened") {
|
|
474
|
+
record.status = labels.mr.state === "merged" ? "merged" : "closed";
|
|
475
|
+
state = policy.terminal?.(ctx, binding, { mr: labels.mr, pipeline: null }) ?? state;
|
|
476
|
+
stopped = true;
|
|
477
|
+
// Recovery does not need a living worker or an enabled discovery watcher.
|
|
478
|
+
} else if (
|
|
479
|
+
!live(process) ||
|
|
480
|
+
gitLabActivationStatus(record.after, labels) === "removed" ||
|
|
481
|
+
(repo.hasDedupKey(activationKey) && !labels.mr.labels.includes(GITLAB_ACTIVE_LABEL))
|
|
482
|
+
) {
|
|
483
|
+
record.status = "stopped";
|
|
484
|
+
state = policy.stopped?.(ctx, binding) ?? state;
|
|
485
|
+
stopped = true;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
delete record.refreshError;
|
|
489
|
+
const terminalStatus =
|
|
490
|
+
stopped && live(process)
|
|
491
|
+
? completionStatus({ ...ctx, state }, policy, records)
|
|
492
|
+
: undefined;
|
|
493
|
+
const saved = await observe(process, {
|
|
494
|
+
projectsJson: JSON.stringify(ctx.projects),
|
|
495
|
+
metadata: { gitlabMaintenance: records },
|
|
496
|
+
...(state !== ctx.state ? { state } : {}),
|
|
497
|
+
...(terminalStatus ? { lifecycleStatus: terminalStatus } : {}),
|
|
498
|
+
...(stopped &&
|
|
499
|
+
!terminalStatus &&
|
|
500
|
+
live(process) &&
|
|
501
|
+
(process.currentExecution ||
|
|
502
|
+
(process.selectedTurnId !== policy.idleTurnId &&
|
|
503
|
+
(!policy.currentBinding || policy.currentBinding(ctx) === binding.projectKey)))
|
|
504
|
+
? {
|
|
505
|
+
interrupt: {
|
|
506
|
+
turnId: policy.idleTurnId,
|
|
507
|
+
reason: "MR maintenance ownership ended",
|
|
508
|
+
},
|
|
509
|
+
}
|
|
510
|
+
: {}),
|
|
511
|
+
preserveUpdatedAt: !stopped,
|
|
512
|
+
});
|
|
513
|
+
if (!saved.ok) continue;
|
|
514
|
+
let fresh = deps.processes.getById(process.id);
|
|
515
|
+
if (!fresh) continue;
|
|
516
|
+
// A deleted MR has no labels, discussions or publication to reconcile.
|
|
517
|
+
if (record.status === "deleted") continue;
|
|
518
|
+
const remoteWriteContext = <T extends object>(payload: T) => ({
|
|
519
|
+
client,
|
|
520
|
+
writes: ctx.externalWrites,
|
|
521
|
+
instanceId: process.id,
|
|
522
|
+
projectId: binding.projectId,
|
|
523
|
+
iid: binding.iid,
|
|
524
|
+
...payload,
|
|
525
|
+
signal: ctx.signal,
|
|
526
|
+
beforeWrite: () =>
|
|
527
|
+
service.assertOwnership(fresh?.id ?? "", binding.projectKey, ctx.signal),
|
|
528
|
+
});
|
|
529
|
+
await ensureGitLabMaintenanceLabels({
|
|
530
|
+
client,
|
|
531
|
+
writes: ctx.externalWrites,
|
|
532
|
+
projectId: binding.projectId,
|
|
533
|
+
iid: binding.iid,
|
|
534
|
+
after: record.after,
|
|
535
|
+
status: record.status,
|
|
536
|
+
writeKey:
|
|
537
|
+
record.status === "active"
|
|
538
|
+
? activationKey
|
|
539
|
+
: `gitlab:${record.status}:${process.id}:${binding.projectKey}:${binding.iid}`,
|
|
540
|
+
guard: async () => same(fresh as ProcessInstance),
|
|
541
|
+
signal: ctx.signal,
|
|
542
|
+
});
|
|
543
|
+
if (!live(fresh) || record.status !== "active") {
|
|
544
|
+
scheduleNext(key, process, settings);
|
|
545
|
+
continue;
|
|
546
|
+
}
|
|
547
|
+
ctx = context(fresh, policy);
|
|
548
|
+
const observation = policy.assess
|
|
549
|
+
? await policy.assess(ctx, binding)
|
|
550
|
+
: await observeMergeRequest(client, binding.projectId, binding.iid, ctx.signal);
|
|
551
|
+
const eligible = policy.eligible?.(ctx, binding, observation) ?? true;
|
|
552
|
+
const feedback = eligible
|
|
553
|
+
? pendingGitLabFeedback(
|
|
554
|
+
"feedback" in observation
|
|
555
|
+
? ((observation.feedback as GitLabFeedback[]) ?? [])
|
|
556
|
+
: await client.listMergeRequestFeedback(
|
|
557
|
+
binding.projectId,
|
|
558
|
+
binding.iid,
|
|
559
|
+
ctx.signal,
|
|
560
|
+
),
|
|
561
|
+
Math.max(record.cursor, settings.cursor ?? 0),
|
|
562
|
+
settings.since,
|
|
563
|
+
)
|
|
564
|
+
: [];
|
|
565
|
+
for (const note of feedback) {
|
|
566
|
+
await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
|
|
567
|
+
await ensureGitLabSeenReaction(remoteWriteContext({ noteId: note.id }));
|
|
568
|
+
}
|
|
569
|
+
const ready = gitLabFeedbackReadyAt(feedback, settings.quietPeriodMs ?? 120_000);
|
|
570
|
+
const targetIntegrated =
|
|
571
|
+
observation.targetHead &&
|
|
572
|
+
client.getMergeBase &&
|
|
573
|
+
observation.mr.source_project_id === observation.mr.target_project_id &&
|
|
574
|
+
(observation.mr.has_conflicts ||
|
|
575
|
+
["conflict", "need_rebase"].includes(observation.mr.detailed_merge_status ?? ""))
|
|
576
|
+
? (
|
|
577
|
+
await client.getMergeBase(
|
|
578
|
+
observation.mr.source_project_id,
|
|
579
|
+
[observation.mr.sha, observation.targetHead],
|
|
580
|
+
ctx.signal,
|
|
581
|
+
)
|
|
582
|
+
).id === observation.targetHead
|
|
583
|
+
: false;
|
|
584
|
+
const observed = {
|
|
585
|
+
...observation,
|
|
586
|
+
targetIntegrated,
|
|
587
|
+
projectKey: binding.projectKey,
|
|
588
|
+
observationKey: observationKey(observation),
|
|
589
|
+
feedback: ready !== null && ready <= now() ? feedback : [],
|
|
590
|
+
};
|
|
591
|
+
const decision = policy.observe(ctx, binding, observed);
|
|
592
|
+
record.observation = observed;
|
|
593
|
+
record.pendingFeedback = feedback;
|
|
594
|
+
const observedRecords = { ...maintenanceRecords(fresh), [binding.projectKey]: record };
|
|
595
|
+
const updated = await observe(fresh, {
|
|
596
|
+
projectsJson: JSON.stringify(ctx.projects),
|
|
597
|
+
metadata: { gitlabMaintenance: observedRecords },
|
|
598
|
+
...(!fresh.currentExecution && decision.state !== ctx.state && !decision.action
|
|
599
|
+
? { state: decision.state }
|
|
600
|
+
: {}),
|
|
601
|
+
preserveUpdatedAt: true,
|
|
602
|
+
});
|
|
603
|
+
if (!updated.ok) continue;
|
|
604
|
+
fresh = deps.processes.getById(process.id);
|
|
605
|
+
if (!fresh) continue;
|
|
606
|
+
if (
|
|
607
|
+
eligible &&
|
|
608
|
+
decision.action &&
|
|
609
|
+
fresh.lifecycleStatus === "waiting" &&
|
|
610
|
+
unchangedWork(fresh, ctx.process)
|
|
611
|
+
) {
|
|
612
|
+
const destination =
|
|
613
|
+
policy.destinations[decision.action as keyof typeof policy.destinations] ??
|
|
614
|
+
decision.action;
|
|
615
|
+
const armed = deps.externalSources
|
|
616
|
+
.listArmed(policy.sourceKind ?? GITLAB_MAINTAINED_KIND)
|
|
617
|
+
.find(
|
|
618
|
+
(item) => item.instanceId === process.id && item.externalActionId === destination,
|
|
619
|
+
);
|
|
620
|
+
if (armed) {
|
|
621
|
+
await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
|
|
622
|
+
const fired = await deps.externalSources.fire({
|
|
623
|
+
instanceId: fresh.id,
|
|
624
|
+
armingId: armed.id,
|
|
625
|
+
generation: armed.generation,
|
|
626
|
+
event: { ...decision.event, state: decision.state },
|
|
627
|
+
mergeKey: `${binding.projectKey}:${observed.observationKey}:${feedback.map((note) => note.id)}`,
|
|
628
|
+
});
|
|
629
|
+
if (!fired.ok) continue;
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
fresh = deps.processes.getById(process.id);
|
|
633
|
+
if (!fresh || !live(fresh)) continue;
|
|
634
|
+
ctx = context(fresh, policy);
|
|
635
|
+
for (const message of eligible ? (policy.messages?.(ctx, binding) ?? []) : []) {
|
|
636
|
+
await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
|
|
637
|
+
await ensureGitLabComment(remoteWriteContext(message));
|
|
638
|
+
}
|
|
639
|
+
const settledState = eligible
|
|
640
|
+
? (policy.settled?.(ctx, binding) ?? ctx.state)
|
|
641
|
+
: ctx.state;
|
|
642
|
+
if (!fresh.currentExecution && settledState !== ctx.state)
|
|
643
|
+
await observe(fresh, { state: settledState });
|
|
644
|
+
fresh = deps.processes.getById(process.id);
|
|
645
|
+
if (
|
|
646
|
+
fresh &&
|
|
647
|
+
eligible &&
|
|
648
|
+
policy.retry &&
|
|
649
|
+
fresh.lifecycleStatus === "error" &&
|
|
650
|
+
fresh.currentExecution
|
|
651
|
+
) {
|
|
652
|
+
const retry = asUnknownRecord(fresh.metadata?.gitlabMaintenanceRetry) ?? {};
|
|
653
|
+
const attempts = Number(retry.attempts ?? 0);
|
|
654
|
+
if (retry.executionId !== fresh.currentExecution.id) {
|
|
655
|
+
await observe(fresh, {
|
|
656
|
+
metadata: {
|
|
657
|
+
gitlabMaintenanceRetry: {
|
|
658
|
+
attempts,
|
|
659
|
+
executionId: fresh.currentExecution.id,
|
|
660
|
+
nextAt: now() + Math.min(300_000, 30_000 * 2 ** attempts),
|
|
661
|
+
attempted: false,
|
|
662
|
+
},
|
|
663
|
+
},
|
|
664
|
+
preserveUpdatedAt: true,
|
|
665
|
+
});
|
|
666
|
+
} else if (
|
|
667
|
+
!retry.attempted &&
|
|
668
|
+
attempts < policy.retry.maxAttempts &&
|
|
669
|
+
Number(retry.nextAt) <= now()
|
|
670
|
+
) {
|
|
671
|
+
await service.assertOwnership(fresh.id, binding.projectKey, ctx.signal);
|
|
672
|
+
const saved = await observe(fresh, {
|
|
673
|
+
metadata: {
|
|
674
|
+
gitlabMaintenanceRetry: { ...retry, attempts: attempts + 1, attempted: true },
|
|
675
|
+
},
|
|
676
|
+
});
|
|
677
|
+
if (saved.ok) await deps.commands.retryProcess(fresh.id);
|
|
678
|
+
}
|
|
679
|
+
} else if (
|
|
680
|
+
fresh?.lifecycleStatus === "waiting" &&
|
|
681
|
+
!fresh.currentExecution &&
|
|
682
|
+
fresh.selectedTurnId === policy.idleTurnId &&
|
|
683
|
+
fresh.metadata?.gitlabMaintenanceRetry
|
|
684
|
+
) {
|
|
685
|
+
await observe(fresh, {
|
|
686
|
+
metadata: { gitlabMaintenanceRetry: null },
|
|
687
|
+
preserveUpdatedAt: true,
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
scheduleNext(key, process, settings);
|
|
691
|
+
} catch (error) {
|
|
692
|
+
const message =
|
|
693
|
+
error instanceof Error ? error.message : "GitLab maintenance unavailable";
|
|
694
|
+
const failures = (previous?.failures ?? 0) + 1;
|
|
695
|
+
due.set(key, {
|
|
696
|
+
at: now() + Math.min(300_000, 30_000 * 2 ** Math.min(failures - 1, 4)),
|
|
697
|
+
failures,
|
|
698
|
+
inputs: workKey(deps.processes.getById(snapshot.id) ?? snapshot),
|
|
699
|
+
});
|
|
700
|
+
const fresh = deps.processes.getById(snapshot.id);
|
|
701
|
+
if (fresh) {
|
|
702
|
+
const records = structuredClone(maintenanceRecords(fresh));
|
|
703
|
+
if (records[binding.projectKey]) {
|
|
704
|
+
records[binding.projectKey].refreshError = message;
|
|
705
|
+
await observe(fresh, { metadata: { gitlabMaintenance: records } });
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
result.errors.push(`${key}:${message}`);
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
let current = deps.processes.getById(snapshot.id);
|
|
712
|
+
if (
|
|
713
|
+
current &&
|
|
714
|
+
!current.metadata?.gitlabMaintenanceCompleted &&
|
|
715
|
+
bindings(context(current, policy), policy).length
|
|
716
|
+
) {
|
|
717
|
+
try {
|
|
718
|
+
ctx = context(current, policy);
|
|
719
|
+
const records = maintenanceRecords(current);
|
|
720
|
+
const schedule = completionDue.get(current.id);
|
|
721
|
+
const pureStatus = completionStatus(ctx, policy, records);
|
|
722
|
+
if (
|
|
723
|
+
schedule &&
|
|
724
|
+
schedule.at > now() &&
|
|
725
|
+
(schedule.failures > 0 || (!pureStatus && live(current)))
|
|
726
|
+
)
|
|
727
|
+
continue;
|
|
728
|
+
const status =
|
|
729
|
+
pureStatus ??
|
|
730
|
+
(live(current) && (await policy.cancelled?.(ctx)) ? "aborted" : undefined);
|
|
731
|
+
if (status && live(current)) {
|
|
732
|
+
const ended = await observe(current, { lifecycleStatus: status });
|
|
733
|
+
if (!ended.ok) continue;
|
|
734
|
+
current = deps.processes.getById(current.id);
|
|
735
|
+
}
|
|
736
|
+
if (current && (status || !live(current))) {
|
|
737
|
+
await policy.complete?.(context(current, policy), maintenanceRecords(current));
|
|
738
|
+
await observe(current, {
|
|
739
|
+
metadata: { gitlabMaintenanceCompleted: true },
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
completionDue.set(snapshot.id, { at: now() + 30_000, failures: 0 });
|
|
743
|
+
} catch (error) {
|
|
744
|
+
const failures = (completionDue.get(snapshot.id)?.failures ?? 0) + 1;
|
|
745
|
+
completionDue.set(snapshot.id, {
|
|
746
|
+
at: now() + Math.min(300_000, 30_000 * 2 ** Math.min(failures - 1, 4)),
|
|
747
|
+
failures,
|
|
748
|
+
});
|
|
749
|
+
result.errors.push(
|
|
750
|
+
`${snapshot.id}:${error instanceof Error ? error.message : "Completion delivery unavailable"}`,
|
|
751
|
+
);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
return result;
|
|
756
|
+
},
|
|
757
|
+
});
|
|
758
|
+
return { ...service, /** @internal */ poll: () => polling.poll() };
|
|
759
|
+
}
|