@leitwerk-dev/gitlab 0.2.1 → 0.3.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/src/external.ts CHANGED
@@ -2,10 +2,39 @@ import {
2
2
  type CoreServerSetupDeps,
3
3
  createExternalSourcePollReporter,
4
4
  type ExternalActionSource,
5
+ type ExternalSourceArmingLike,
5
6
  } from "@leitwerk-dev/process-sdk";
7
+ import { type ConflictEvidence, conflictKey } from "@leitwerk-dev/repository-rebase";
6
8
  import { emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
7
9
  import type { GitLabIntegration } from "./capability.js";
8
10
  import { type GitLabFeedback, type GitLabObservation, observeMergeRequest } from "./client.js";
11
+ import { createGitLabIssueDiscovery } from "./issue-watcher.js";
12
+ /** @public */
13
+ export interface GitLabDeliveryObservation extends GitLabObservation {
14
+ /** @public */
15
+ observationKey?: string;
16
+ /** @public */
17
+ feedback?: GitLabFeedback[];
18
+ /** @public */
19
+ conflict?: ConflictEvidence;
20
+ }
21
+ /** @public */
22
+ export const GITLAB_ISSUE_CANCELLED_KIND = "@leitwerk-dev/gitlab.issue-cancelled";
23
+ /** @public */
24
+ export interface GitLabIssueCancelledConfig {
25
+ /** @public */
26
+ profile: string;
27
+ /** @public */
28
+ projectId: number;
29
+ /** @public */
30
+ issueIid: number;
31
+ /** @public */
32
+ iid: number;
33
+ /** @public */
34
+ triggerLabel: string;
35
+ /** @public */
36
+ pollInterval?: string;
37
+ }
9
38
  /** @internal */
10
39
  export const GITLAB_MR_KIND = "@leitwerk-dev/gitlab.merge-request";
11
40
  /** @public */
@@ -20,9 +49,26 @@ export interface GitLabSourceConfig {
20
49
  pollInterval?: string;
21
50
  /** @public */
22
51
  afterKey?: string;
23
- /** Optional timer also wakes retry work when GitLab facts have not changed. @public */
52
+ /** Optional timer also wakes retry work when GitLab facts have not changed. */
53
+ /** @public */
24
54
  wakeAt?: number;
25
55
  /** @public */
56
+ delivery?: {
57
+ /** @public */
58
+ headSha: string;
59
+ /** @public */
60
+ owner: string;
61
+ /** @public */
62
+ repo: string;
63
+ /** @public */
64
+ headBranch: string;
65
+ /** @public */
66
+ baseBranch: string;
67
+ /** @public */
68
+ lastConflictKey?: string | null;
69
+ };
70
+ /** @public */
71
+ /** @public */
26
72
  feedback?: {
27
73
  /** @public */
28
74
  afterId: number;
@@ -32,7 +78,8 @@ export interface GitLabSourceConfig {
32
78
  quietPeriodMs: number;
33
79
  };
34
80
  }
35
- /** A trailing quiet period survives restarts because it uses the newest unseen note's timestamp. @public */
81
+ /** A trailing quiet period survives restarts because it uses the newest unseen note's timestamp. */
82
+ /** @public */
36
83
  export function pendingGitLabFeedback(
37
84
  items: GitLabFeedback[],
38
85
  afterId: number,
@@ -70,19 +117,40 @@ export const observationKey = ({ mr, pipeline, targetHead }: GitLabObservation):
70
117
  ]);
71
118
  /** @public */
72
119
  export const gitlabExternal = {
120
+ /** @public */
121
+ issueCancelled<P, S>(
122
+ /** @public */
123
+ /** @public */
124
+ resolve: (ctx: {
125
+ /** @public */
126
+ params: P;
127
+ /** @public */
128
+ state: S;
129
+ }) => GitLabIssueCancelledConfig,
130
+ ): ExternalActionSource<P, S, unknown> {
131
+ return {
132
+ kind: GITLAB_ISSUE_CANCELLED_KIND,
133
+ label: "GitLab source issue cancelled",
134
+ config: {},
135
+ inputMode: "none",
136
+ resolve,
137
+ };
138
+ },
73
139
  /** @public */
74
140
  mergeRequest<P, S>(
141
+ /** @public */
142
+ /** @public */
75
143
  resolve: (ctx: {
76
144
  /** @public */
77
145
  params: P;
78
146
  /** @public */
79
147
  state: S;
80
148
  }) => GitLabSourceConfig,
81
- ): ExternalActionSource<P, S, GitLabObservation> {
149
+ ): ExternalActionSource<P, S, GitLabDeliveryObservation> {
82
150
  return {
83
151
  kind: GITLAB_MR_KIND,
84
152
  label: "GitLab merge request",
85
- description: "Observe MR state, source/target heads, mergeability and revision-correlated CI",
153
+ description: "Observe MR state, current source head and revision-correlated CI",
86
154
  config: {},
87
155
  inputMode: "none",
88
156
  resolve,
@@ -93,13 +161,15 @@ export const gitlabExternal = {
93
161
  export function createGitLabProvider(
94
162
  deps: CoreServerSetupDeps,
95
163
  integration: GitLabIntegration,
164
+ /** @public */
165
+ /** @public */
96
166
  options: {
97
- /** @internal */
98
- now?: () => number;
167
+ /** @internal */ now?: () => number;
99
168
  } = {},
100
169
  ) {
101
170
  const schedule = new Map<string, { at: number; failures: number }>();
102
171
  const now = options.now ?? Date.now;
172
+ const discover = createGitLabIssueDiscovery(deps, integration, now);
103
173
  return deps.polling.create({
104
174
  id: "gitlab",
105
175
  pollInterval: () => "5s",
@@ -107,7 +177,27 @@ export function createGitLabProvider(
107
177
  defaultIntervalMs: 5000,
108
178
  async pollOnce() {
109
179
  const result = emptyPollResult();
110
- const report = createExternalSourcePollReporter(deps.externalSources, result);
180
+ try {
181
+ await discover(result);
182
+ } catch (error) {
183
+ result.errors.push(error instanceof Error ? error.message : "GitLab discovery failed");
184
+ }
185
+ const reporter = createExternalSourcePollReporter(deps.externalSources, result, {
186
+ forwardGeneration: true,
187
+ });
188
+ const current = (armed: ExternalSourceArmingLike) =>
189
+ [GITLAB_MR_KIND, GITLAB_ISSUE_CANCELLED_KIND].some((kind) =>
190
+ reporter.isCurrent(kind, armed),
191
+ );
192
+ const report = {
193
+ ...reporter,
194
+ fire(armed: ExternalSourceArmingLike, event: Record<string, unknown>, mergeKey: string) {
195
+ return current(armed) ? reporter.fire(armed, event, mergeKey) : Promise.resolve(false);
196
+ },
197
+ observe(armed: ExternalSourceArmingLike, input: Parameters<typeof reporter.observe>[1]) {
198
+ if (current(armed)) return reporter.observe(armed, input);
199
+ },
200
+ };
111
201
  await report.poll(GITLAB_MR_KIND, async (armed) => {
112
202
  const c = armed.resolved as unknown as GitLabSourceConfig;
113
203
  if (
@@ -126,7 +216,40 @@ export function createGitLabProvider(
126
216
  c.projectId,
127
217
  c.iid,
128
218
  );
129
- const observedKey = observationKey(observation);
219
+ let conflict: ConflictEvidence | undefined;
220
+ const client = integration.client(c.profile);
221
+ if (
222
+ c.delivery &&
223
+ observation.mr.state === "opened" &&
224
+ observation.mr.sha === c.delivery.headSha &&
225
+ (observation.mr.has_conflicts === true ||
226
+ observation.mr.detailed_merge_status === "conflict")
227
+ ) {
228
+ const mr = observation.mr;
229
+ const d = c.delivery;
230
+ if (
231
+ mr.source_project_id !== c.projectId ||
232
+ mr.target_project_id !== c.projectId ||
233
+ mr.source_branch !== d.headBranch ||
234
+ mr.target_branch !== d.baseBranch
235
+ )
236
+ throw new Error("GitLab merge request branches changed");
237
+ const base = await client.getBranch(c.projectId, d.baseBranch);
238
+ const evidence: ConflictEvidence = {
239
+ owner: d.owner,
240
+ repo: d.repo,
241
+ prNumber: c.iid,
242
+ headBranch: d.headBranch,
243
+ baseBranch: d.baseBranch,
244
+ headSha: mr.sha,
245
+ baseSha: base.commit.id,
246
+ url: mr.web_url,
247
+ };
248
+ if (conflictKey(evidence) !== d.lastConflictKey) conflict = evidence;
249
+ }
250
+ const observedKey =
251
+ observationKey(observation) +
252
+ (c.delivery ? `:${conflict ? conflictKey(conflict) : ""}` : "");
130
253
  const feedback =
131
254
  c.feedback && observation.mr.state === "opened"
132
255
  ? pendingGitLabFeedback(
@@ -140,6 +263,10 @@ export function createGitLabProvider(
140
263
  c.feedback?.quietPeriodMs ?? 120_000,
141
264
  );
142
265
  const feedbackReady = feedbackReadyAt !== null && feedbackReadyAt <= now();
266
+ if (c.delivery) {
267
+ const fresh = await client.getMergeRequest(c.projectId, c.iid);
268
+ if (fresh.sha !== observation.mr.sha || fresh.state !== observation.mr.state) return;
269
+ }
143
270
  await report.observe(armed, {
144
271
  observation: {
145
272
  summary: `${observation.mr.state} · ${observation.pipeline?.status ?? "no current pipeline"}`,
@@ -155,7 +282,16 @@ export function createGitLabProvider(
155
282
  )
156
283
  await report.fire(
157
284
  armed,
158
- { ...observation },
285
+ {
286
+ ...observation,
287
+ ...(c.delivery
288
+ ? {
289
+ observationKey: observedKey,
290
+ feedback: feedbackReady ? feedback : [],
291
+ ...(conflict ? { conflict } : {}),
292
+ }
293
+ : {}),
294
+ },
159
295
  `${observedKey}:${c.wakeAt ?? ""}:${feedbackReady ? feedback.map((item) => item.id).join(",") : ""}`,
160
296
  );
161
297
  schedule.set(key, {
@@ -174,6 +310,26 @@ export function createGitLabProvider(
174
310
  throw error;
175
311
  }
176
312
  });
313
+ await report.poll(GITLAB_ISSUE_CANCELLED_KIND, async (armed) => {
314
+ const c = armed.resolved as unknown as GitLabIssueCancelledConfig;
315
+ const key = `${armed.instanceId}:${armed.id}:${armed.generation ?? ""}`;
316
+ if ((schedule.get(key)?.at ?? 0) > now()) return;
317
+ const client = integration.client(c.profile);
318
+ const issue = await client.getIssue(c.projectId, c.issueIid);
319
+ if (issue.state !== "opened" || !issue.labels.includes(c.triggerLabel)) {
320
+ const mr = await client.getMergeRequest(c.projectId, c.iid);
321
+ if (mr.state !== "opened") return;
322
+ await report.fire(
323
+ armed,
324
+ { issue },
325
+ `${issue.iid}:${issue.state}:${issue.labels.includes(c.triggerLabel)}`,
326
+ );
327
+ }
328
+ schedule.set(key, {
329
+ at: now() + parseDurationMs(c.pollInterval ?? "30s", 30000),
330
+ failures: 0,
331
+ });
332
+ });
177
333
  return result;
178
334
  },
179
335
  });
package/src/index.ts CHANGED
@@ -53,12 +53,15 @@ export type {
53
53
  GitLabProject,
54
54
  } from "./client.js";
55
55
  export { observeMergeRequest } from "./client.js";
56
+ export type { GitLabDeliveryObservation } from "./external.js";
56
57
  export {
57
58
  gitLabFeedbackReadyAt,
58
59
  gitlabExternal,
59
60
  observationKey,
60
61
  pendingGitLabFeedback,
61
62
  } from "./external.js";
63
+ export type { GitLabIssueWatcherEvent } from "./issue-watcher.js";
64
+ export { gitlabIssueExternalId, gitlabIssueWatcherSource } from "./issue-watcher.js";
62
65
  export type { GitLabSelection } from "./selection.js";
63
66
  export {
64
67
  parseGitLabSelection,
@@ -0,0 +1,152 @@
1
+ import { asUnknownRecord } from "@leitwerk-dev/domain";
2
+ import {
3
+ type CoreServerSetupDeps,
4
+ defineProcessWatcherSource,
5
+ parseProcessWatcherLaunchModelConfig,
6
+ } from "@leitwerk-dev/process-sdk";
7
+ import { type emptyPollResult, parseDurationMs } from "@leitwerk-dev/watcher-utils";
8
+ import type { GitLabIntegration } from "./capability.js";
9
+ import type { GitLabIssue, GitLabProject } from "./client.js";
10
+ import { type GitLabSelection, parseGitLabSelection, selectGitLabProjects } from "./selection.js";
11
+ /** @public */
12
+ export interface GitLabIssueWatcherConfig extends GitLabSelection {
13
+ /** @public */
14
+ profile: string;
15
+ /** @public */
16
+ pollInterval: string;
17
+ /** @public */
18
+ /** @public */
19
+ labels: {
20
+ /** @public */ trigger: string /** @public */;
21
+ /** @public */
22
+ done: string;
23
+ };
24
+ }
25
+ /** @public */
26
+ export interface GitLabIssueWatcherEvent {
27
+ /** @public */
28
+ profile: string;
29
+ /** @public */
30
+ repository: GitLabProject;
31
+ /** @public */
32
+ issue: GitLabIssue;
33
+ /** @public */
34
+ /** @public */
35
+ labels: {
36
+ /** @public */ trigger: string /** @public */;
37
+ /** @public */
38
+ done: string;
39
+ };
40
+ }
41
+ /** @public */
42
+ export const gitlabIssueExternalId = (origin: string, projectId: number, iid: number) =>
43
+ `gitlab:${origin}:${projectId}#${iid}`;
44
+ /** @public */
45
+ export const gitlabIssueWatcherSource = defineProcessWatcherSource<
46
+ GitLabIssueWatcherConfig,
47
+ GitLabIssueWatcherEvent
48
+ >({
49
+ id: "@leitwerk-dev/gitlab.issue",
50
+ label: "GitLab issue",
51
+ parseConfig(raw) {
52
+ const c = asUnknownRecord(raw);
53
+ if (!c || typeof c.enabled !== "boolean") throw new Error("GitLab watcher requires enabled");
54
+ const text = (value: unknown, name: string) => {
55
+ if (typeof value !== "string" || !value.trim())
56
+ throw new Error(`GitLab watcher requires ${name}`);
57
+ return value.trim();
58
+ };
59
+ const labels = asUnknownRecord(c.labels) ?? {};
60
+ const trigger = text(labels.trigger, "labels.trigger");
61
+ const done = text(labels.done, "labels.done");
62
+ if (trigger === done || trigger.includes(",") || done.includes(","))
63
+ throw new Error("GitLab trigger/done labels must be distinct and contain no comma");
64
+ const pollInterval = text(c.poll_interval ?? "30s", "poll_interval");
65
+ if (parseDurationMs(pollInterval, -1) <= 0) throw new Error("Invalid GitLab polling interval");
66
+ return {
67
+ enabled: c.enabled,
68
+ config: {
69
+ ...parseGitLabSelection(c),
70
+ profile: text(c.profile, "profile"),
71
+ pollInterval,
72
+ labels: { trigger, done },
73
+ },
74
+ launchModelConfig: parseProcessWatcherLaunchModelConfig(c.launch),
75
+ };
76
+ },
77
+ presentConfig(c) {
78
+ return {
79
+ targetSummary: `Profile ${c.profile} · trigger ${c.labels.trigger}`,
80
+ details: [
81
+ { label: "Projects", value: c.projects.include.join(", ") || "selected groups" },
82
+ { label: "Groups", value: c.groups.include.join(", ") || "none" },
83
+ ],
84
+ };
85
+ },
86
+ });
87
+ /** @public */
88
+ export function createGitLabIssueDiscovery(
89
+ deps: CoreServerSetupDeps,
90
+ integration: GitLabIntegration,
91
+ now: () => number,
92
+ ) {
93
+ const due = new Map<string, number>();
94
+ return async (result: ReturnType<typeof emptyPollResult>) => {
95
+ for (const watcher of deps.processWatchers?.listBySource(gitlabIssueWatcherSource) ?? []) {
96
+ if (!watcher.enabled) continue;
97
+ const key = `${watcher.processId}:${watcher.watcherId}`;
98
+ const c = watcher.config;
99
+ if ((due.get(key) ?? 0) > now()) continue;
100
+ due.set(key, now() + parseDurationMs(c.pollInterval, 30000));
101
+ const client = integration.client(c.profile);
102
+ for (const repository of await selectGitLabProjects(client, c))
103
+ for (const issue of await client.listIssues(repository.id)) {
104
+ if (
105
+ issue.state !== "opened" ||
106
+ !issue.labels.includes(c.labels.trigger) ||
107
+ issue.labels.includes(c.labels.done)
108
+ )
109
+ continue;
110
+ const id = gitlabIssueExternalId(client.baseUrl, repository.id, issue.iid);
111
+ if (deps.processes.listAll().some((p) => p.externalId === id)) {
112
+ result.skipped.push(id);
113
+ continue;
114
+ }
115
+ const guarded = {
116
+ ...watcher,
117
+ async resolveLaunchAttempt(...args: Parameters<typeof watcher.resolveLaunchAttempt>) {
118
+ const attempt = await watcher.resolveLaunchAttempt(...args);
119
+ if (!attempt) return null;
120
+ return {
121
+ ...attempt,
122
+ preparationChecks: [
123
+ ...attempt.preparationChecks,
124
+ {
125
+ id: "gitlab-issue-eligibility",
126
+ label: "Recheck GitLab source issue",
127
+ async run() {
128
+ const fresh = await client.getIssue(repository.id, issue.iid);
129
+ if (
130
+ fresh.state !== "opened" ||
131
+ !fresh.labels.includes(c.labels.trigger) ||
132
+ fresh.labels.includes(c.labels.done)
133
+ )
134
+ throw new Error("GitLab source issue eligibility changed before launch");
135
+ },
136
+ },
137
+ ],
138
+ };
139
+ },
140
+ };
141
+ const launched = await deps.launchRuns.startWatcher(
142
+ guarded,
143
+ { profile: c.profile, repository, issue, labels: c.labels },
144
+ { idempotencyKey: id },
145
+ );
146
+ if (launched.error) result.errors.push(`${id}:launch_failed`);
147
+ else if (launched.process) result.created.push(id);
148
+ else result.skipped.push(id);
149
+ }
150
+ }
151
+ };
152
+ }
@@ -0,0 +1,70 @@
1
+ import { execFile } from "node:child_process";
2
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { promisify } from "node:util";
6
+ import { repositoryHttpsUrl } from "@leitwerk-dev/process-sdk";
7
+
8
+ const exec = promisify(execFile);
9
+ /** Credentials stay in the child environment and never appear in URLs or error output. */
10
+ export async function preflightGitLabRepository(input: {
11
+ url: string;
12
+ origin: string;
13
+ token: string;
14
+ baseBranch: string;
15
+ workBranch: string;
16
+ signal?: AbortSignal;
17
+ }) {
18
+ const url = repositoryHttpsUrl(input.url);
19
+ if (url.origin !== input.origin)
20
+ throw new Error("GitLab repository origin does not match its profile");
21
+ const directory = await mkdtemp(join(tmpdir(), "leitwerk-gitlab-preflight-"));
22
+ try {
23
+ const askpass = join(directory, "askpass");
24
+ await writeFile(
25
+ askpass,
26
+ '#!/bin/sh\ncase "$1" in *Username*) printf "%s\\n" oauth2;; *) printf "%s\\n" "$LEITWERK_GITLAB_PREFLIGHT_TOKEN";; esac\n',
27
+ { mode: 0o700 },
28
+ );
29
+ const env = {
30
+ ...process.env,
31
+ GIT_CONFIG_NOSYSTEM: "1",
32
+ GIT_CONFIG_GLOBAL: "/dev/null",
33
+ GIT_TERMINAL_PROMPT: "0",
34
+ GIT_ASKPASS: askpass,
35
+ LEITWERK_GITLAB_PREFLIGHT_TOKEN: input.token,
36
+ };
37
+ const git = (args: string[]) =>
38
+ exec("git", ["-c", "credential.helper=", "-c", "http.followRedirects=false", ...args], {
39
+ env,
40
+ signal: input.signal,
41
+ });
42
+ await git(["check-ref-format", `refs/heads/${input.baseBranch}`]);
43
+ await git(["check-ref-format", `refs/heads/${input.workBranch}`]);
44
+ await git(["ls-remote", "--exit-code", input.url, `refs/heads/${input.baseBranch}`]);
45
+ await git(["init", "--quiet", directory]);
46
+ await git([
47
+ "-C",
48
+ directory,
49
+ "fetch",
50
+ "--quiet",
51
+ "--depth=1",
52
+ input.url,
53
+ `refs/heads/${input.baseBranch}`,
54
+ ]);
55
+ await git([
56
+ "-C",
57
+ directory,
58
+ "push",
59
+ "--dry-run",
60
+ input.url,
61
+ `FETCH_HEAD:refs/heads/${input.workBranch}`,
62
+ ]);
63
+ } catch {
64
+ throw new Error(
65
+ "GitLab HTTPS read/write admission failed; check repository access and write_repository scope",
66
+ );
67
+ } finally {
68
+ await rm(directory, { recursive: true, force: true });
69
+ }
70
+ }
package/src/setup.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { coreHostCapabilities, type ServerExtensionAPI } from "@leitwerk-dev/process-sdk";
2
2
  import { type GitLabIntegration, gitlabIntegration } from "./capability.js";
3
+ import { registerGitLabDeliveryTools } from "./delivery-tools.js";
3
4
  import { createGitLabProvider } from "./external.js";
4
5
  import { registerGitLabTools } from "./tools.js";
5
6
 
@@ -16,5 +17,6 @@ export function setupGitLabIntegration(
16
17
  const deps = api.get(coreHostCapabilities.serverSetup);
17
18
  if (!deps || Array.isArray(deps)) return;
18
19
  registerGitLabTools(api, integration);
20
+ registerGitLabDeliveryTools(api, integration, deps.projects);
19
21
  return createGitLabProvider(deps, integration, options);
20
22
  }