plugin-workflow-ci 0.0.0-stage → 0.2.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.
Files changed (60) hide show
  1. package/client-v2.js +1 -0
  2. package/client.js +1 -0
  3. package/dist/client/index.js +10 -0
  4. package/dist/client-v2/index.js +10 -0
  5. package/dist/externalVersion.js +21 -0
  6. package/dist/index.js +48 -0
  7. package/dist/locale/en-US.json +105 -0
  8. package/dist/locale/vi-VN.json +105 -0
  9. package/dist/locale/zh-CN.json +105 -0
  10. package/dist/server/actions/ci-manager.js +307 -0
  11. package/dist/server/collections/ci-gate-runs.js +85 -0
  12. package/dist/server/collections/ci-git-feedback-outbox.js +51 -0
  13. package/dist/server/collections/ci-pipelines.js +88 -0
  14. package/dist/server/index.js +62 -0
  15. package/dist/server/instructions/CiInstructions.js +180 -0
  16. package/dist/server/migrations/20261206000001-harden-workflow-ci-v020.js +91 -0
  17. package/dist/server/plugin.js +255 -0
  18. package/dist/server/services/AiTriageService.js +215 -0
  19. package/dist/server/services/CiGateWorkflowService.js +1776 -0
  20. package/dist/server/services/EphemeralContainerService.js +891 -0
  21. package/dist/server/services/GitFeedbackService.js +995 -0
  22. package/dist/server/services/constants-internal.js +65 -0
  23. package/dist/shared/collection-schemas.js +125 -0
  24. package/dist/shared/constants.js +120 -0
  25. package/dist/shared/runtime-context.js +67 -0
  26. package/dist/shared/types.js +24 -0
  27. package/dist/shared/ui/CiPipelinesSettingsView.js +700 -0
  28. package/package.json +58 -4
  29. package/server.js +1 -0
  30. package/src/client/index.tsx +10 -0
  31. package/src/client/locale.ts +31 -0
  32. package/src/client/plugin.tsx +62 -0
  33. package/src/client/workflow.tsx +119 -0
  34. package/src/client-v2/index.tsx +10 -0
  35. package/src/client-v2/locale.ts +32 -0
  36. package/src/client-v2/plugin.tsx +77 -0
  37. package/src/client-v2/workflow.tsx +124 -0
  38. package/src/index.ts +11 -0
  39. package/src/locale/en-US.json +105 -0
  40. package/src/locale/vi-VN.json +105 -0
  41. package/src/locale/zh-CN.json +105 -0
  42. package/src/server/actions/ci-manager.ts +377 -0
  43. package/src/server/collections/ci-gate-runs.ts +65 -0
  44. package/src/server/collections/ci-git-feedback-outbox.ts +31 -0
  45. package/src/server/collections/ci-pipelines.ts +68 -0
  46. package/src/server/index.ts +17 -0
  47. package/src/server/instructions/CiInstructions.ts +180 -0
  48. package/src/server/migrations/20261206000001-harden-workflow-ci-v020.ts +78 -0
  49. package/src/server/plugin.ts +274 -0
  50. package/src/server/services/AiTriageService.ts +254 -0
  51. package/src/server/services/CiGateWorkflowService.ts +2310 -0
  52. package/src/server/services/EphemeralContainerService.ts +1170 -0
  53. package/src/server/services/GitFeedbackService.ts +1224 -0
  54. package/src/server/services/constants-internal.ts +27 -0
  55. package/src/shared/collection-schemas.ts +98 -0
  56. package/src/shared/constants.ts +50 -0
  57. package/src/shared/runtime-context.tsx +55 -0
  58. package/src/shared/types.ts +203 -0
  59. package/src/shared/ui/CiPipelinesSettingsView.tsx +1035 -0
  60. package/README.md +0 -3
@@ -0,0 +1,891 @@
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
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var EphemeralContainerService_exports = {};
28
+ __export(EphemeralContainerService_exports, {
29
+ EphemeralContainerService: () => EphemeralContainerService
30
+ });
31
+ module.exports = __toCommonJS(EphemeralContainerService_exports);
32
+ var import_constants = require("../../shared/constants");
33
+ function isPlainRecord(val) {
34
+ return Boolean(val) && typeof val === "object" && !Array.isArray(val);
35
+ }
36
+ function assertSafeHttpUrl(rawUrl) {
37
+ const parsed = new URL(rawUrl.trim());
38
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
39
+ throw new Error(`Unsupported HTTP URL protocol: ${parsed.protocol}`);
40
+ }
41
+ if (parsed.username || parsed.password) {
42
+ throw new Error("Credentials in URL are not permitted");
43
+ }
44
+ return parsed;
45
+ }
46
+ function demuxDockerLogs(buf) {
47
+ if (!buf || buf.length === 0) return "";
48
+ const multiplexed = buf.length >= 8 && (buf[0] === 0 || buf[0] === 1 || buf[0] === 2) && buf[1] === 0 && buf[2] === 0 && buf[3] === 0;
49
+ if (!multiplexed) return buf.toString("utf8");
50
+ const chunks = [];
51
+ let offset = 0;
52
+ while (offset + 8 <= buf.length) {
53
+ const frameLen = buf.readUInt32BE(offset + 4);
54
+ offset += 8;
55
+ if (offset + frameLen > buf.length) {
56
+ chunks.push(buf.subarray(offset));
57
+ break;
58
+ }
59
+ chunks.push(buf.subarray(offset, offset + frameLen));
60
+ offset += frameLen;
61
+ }
62
+ return Buffer.concat(chunks).toString("utf8");
63
+ }
64
+ function injectLocalPullPolicyInCompose(composeText, repositories) {
65
+ if (!composeText.trim() || repositories.length === 0) return composeText;
66
+ const lines = composeText.split(/\r?\n/);
67
+ const out = [];
68
+ for (let i = 0; i < lines.length; i += 1) {
69
+ const line = lines[i];
70
+ out.push(line);
71
+ const imgMatch = /^(\s*)image\s*:\s*(.+?)(?:\s+#.*)?$/.exec(line);
72
+ if (!imgMatch) continue;
73
+ const indent = imgMatch[1];
74
+ const expr = imgMatch[2].trim().replace(/^['"]|['"]$/g, "");
75
+ if (!repositories.some((repo) => expr.startsWith(`${repo}:`) || expr.startsWith(`${repo}@`) || expr === repo)) {
76
+ continue;
77
+ }
78
+ const nextLine = lines[i + 1] ?? "";
79
+ if (!/^\s*pull_policy\s*:/.test(nextLine)) {
80
+ out.push(`${indent}pull_policy: never`);
81
+ }
82
+ }
83
+ return out.join("\n");
84
+ }
85
+ function pinComposeImageDigests(composeText, digestByRepo) {
86
+ if (!composeText.trim() || digestByRepo.size === 0) return composeText;
87
+ const lines = composeText.split(/\r?\n/);
88
+ return lines.map((line) => {
89
+ const imgMatch = /^(\s*image\s*:\s*)(.+?)(\s+#.*)?$/.exec(line);
90
+ if (!imgMatch) return line;
91
+ const rawExpr = imgMatch[2].trim().replace(/^['"]|['"]$/g, "");
92
+ for (const [repo, digestRef] of digestByRepo.entries()) {
93
+ if (rawExpr === repo || rawExpr.startsWith(`${repo}:`) || rawExpr.startsWith(`${repo}@`)) {
94
+ return `${imgMatch[1]}${digestRef}${imgMatch[3] ?? ""}`;
95
+ }
96
+ }
97
+ return line;
98
+ }).join("\n");
99
+ }
100
+ class EphemeralContainerService {
101
+ constructor(app) {
102
+ this.app = app;
103
+ }
104
+ fetchImpl = (url, init) => fetch(url, init);
105
+ rolloutPollIntervalMs = 1e3;
106
+ rolloutMaxWaitMs = 3e4;
107
+ setHttpFetch(fn) {
108
+ this.fetchImpl = fn;
109
+ }
110
+ hasCollection(name) {
111
+ try {
112
+ return Boolean(this.app.db.getCollection(name));
113
+ } catch {
114
+ return false;
115
+ }
116
+ }
117
+ async decryptSecret(raw) {
118
+ if (typeof raw !== "string" || !raw.trim()) return "";
119
+ const encryptor = this.app.aesEncryptor;
120
+ if (!encryptor) return raw.trim();
121
+ try {
122
+ return await encryptor.decrypt(raw.trim());
123
+ } catch {
124
+ return raw.trim();
125
+ }
126
+ }
127
+ async resolvePortainerAuth(instanceId) {
128
+ if (!this.hasCollection(import_constants.PORTAINER_INSTANCES_COLLECTION)) return null;
129
+ const repo = this.app.db.getRepository(import_constants.PORTAINER_INSTANCES_COLLECTION);
130
+ const record = await repo.findOne({
131
+ filter: instanceId ? { id: instanceId, enabled: true } : { isDefault: true, enabled: true }
132
+ });
133
+ if (!record) return null;
134
+ const baseUrl = assertSafeHttpUrl(String(record.get("baseUrl") || "")).toString().replace(/\/+$/, "");
135
+ const apiKey = await this.decryptSecret(record.get("apiKey"));
136
+ return { baseUrl, apiKey };
137
+ }
138
+ buildRunnerEnvList(params) {
139
+ const customEnv = isPlainRecord(params.pipeline.runnerEnv) ? params.pipeline.runnerEnv : {};
140
+ const merged = {};
141
+ for (const [k, v] of Object.entries(customEnv)) {
142
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) {
143
+ merged[k] = String(v ?? "");
144
+ }
145
+ }
146
+ merged.CI = "true";
147
+ merged.TEST_RUN_ID = String(params.testRunId);
148
+ merged.CI_GATE_RUN_ID = String(params.gateRun.id);
149
+ if (params.groupId) {
150
+ merged.RUNNER_GROUP_ID = params.groupId;
151
+ }
152
+ if (params.attempt !== void 0) {
153
+ merged.RUNNER_ATTEMPT = String(params.attempt);
154
+ }
155
+ merged.TEST_TENANT_KEY = params.tenantKey;
156
+ merged.PG_SCHEMA = params.postgresSchema;
157
+ merged.GIT_COMMIT_SHA = params.gateRun.commitSha;
158
+ merged.GIT_SHORT_SHA = params.gateRun.commitSha.slice(0, 7);
159
+ merged.GIT_BRANCH = params.gateRun.branch;
160
+ if (params.gateRun.mrIid) {
161
+ merged.GIT_MR_IID = String(params.gateRun.mrIid);
162
+ }
163
+ if (params.targetBaseUrl) {
164
+ merged.TARGET_BASE_URL = params.targetBaseUrl;
165
+ }
166
+ merged.NOCOBASE_MANIFEST_URL = params.manifestUrl;
167
+ merged.NOCOBASE_REPORT_URL = params.callbackUrl;
168
+ if (params.callbackToken) {
169
+ merged.NOCOBASE_REPORT_TOKEN = params.callbackToken;
170
+ }
171
+ return merged;
172
+ }
173
+ async launchOneShotContainer(params) {
174
+ var _a;
175
+ const image = String(params.pipeline.runnerImage || "").trim();
176
+ if (!image || !/^[\w./:@-]+$/.test(image) || image.startsWith("-")) {
177
+ throw new Error("Valid runnerImage is required for ephemeral container CI runner");
178
+ }
179
+ const envMap = this.buildRunnerEnvList(params);
180
+ const timeoutMs = Number(params.pipeline.runnerTimeoutMs || import_constants.DEFAULT_CI_TIMEOUT_MS);
181
+ const deadlineMs = Date.now() + timeoutMs + 3e4;
182
+ const cleanGroupSuffix = params.groupId ? `-${params.groupId.replace(/[^a-zA-Z0-9_-]+/g, "-").slice(0, 24)}` : "";
183
+ const attemptSuffix = params.attempt ? `-a${params.attempt}` : "";
184
+ const containerName = `nb-ci-run-${params.gateRun.id}-${params.testRunId}${cleanGroupSuffix}${attemptSuffix}`;
185
+ const cmdString = String(params.pipeline.runnerCommand || "").trim();
186
+ if (params.pipeline.runnerBackend === "cluster_ephemeral") {
187
+ const clusterPlugin = this.app.pm.get("plugin-cluster-manager") || this.app.pm.get("cluster-manager");
188
+ const orchestrator = clusterPlugin == null ? void 0 : clusterPlugin.orchestrator;
189
+ if (!orchestrator) {
190
+ throw new Error("Cluster Manager orchestrator adapter is not active for cluster_ephemeral runner");
191
+ }
192
+ if (typeof orchestrator.launchOneShotRunner === "function") {
193
+ const res = await orchestrator.launchOneShotRunner({
194
+ name: containerName,
195
+ image,
196
+ ...cmdString ? { command: cmdString } : {},
197
+ envVars: envMap,
198
+ networks: params.pipeline.runnerNetwork ? [params.pipeline.runnerNetwork] : [],
199
+ timeoutSeconds: Math.max(10, Math.ceil(timeoutMs / 1e3)),
200
+ deadlineMs,
201
+ labels: {
202
+ "nocobase.workflow-ci": "true",
203
+ "nocobase.workflow-ci.gate-run": String(params.gateRun.id),
204
+ "nocobase.workflow-ci.test-run": String(params.testRunId)
205
+ }
206
+ });
207
+ return {
208
+ launched: true,
209
+ backend: "cluster_ephemeral",
210
+ containerId: res.runnerId,
211
+ containerName: res.runnerName || containerName,
212
+ logs: [`Launched isolated cluster one-shot runner "${res.runnerId}" using image "${image}"`]
213
+ };
214
+ }
215
+ if (params.pipeline.deployGateMode !== "none") {
216
+ throw new Error(
217
+ "Cluster orchestrator does not implement isolated launchOneShotRunner(); refusing unsafe worker scale() fallback on gated pipeline"
218
+ );
219
+ }
220
+ if (!orchestrator.scale) {
221
+ throw new Error("Cluster Manager orchestrator adapter does not support launchOneShotRunner");
222
+ }
223
+ const scaleRes = await orchestrator.scale(
224
+ {
225
+ name: containerName,
226
+ adapter: orchestrator.name === "kubernetes" ? "kubernetes" : "docker",
227
+ image,
228
+ ...cmdString ? { command: cmdString } : {},
229
+ envVars: envMap,
230
+ networks: params.pipeline.runnerNetwork ? [params.pipeline.runnerNetwork] : [],
231
+ volumes: [],
232
+ replicas: 0,
233
+ desiredReplicas: 1,
234
+ enabled: true,
235
+ restartPolicy: "no",
236
+ dockerSecurityOpt: ["no-new-privileges:true"]
237
+ },
238
+ 1
239
+ );
240
+ const createdId = ((_a = scaleRes.containersCreated) == null ? void 0 : _a[0]) || containerName;
241
+ return {
242
+ launched: true,
243
+ backend: "cluster_ephemeral",
244
+ containerId: createdId,
245
+ containerName,
246
+ logs: [`Launched cluster ephemeral CI container "${createdId}" using image "${image}"`]
247
+ };
248
+ }
249
+ const endpointId = Number(params.pipeline.portainerEndpointId || 0);
250
+ if (!Number.isFinite(endpointId) || endpointId <= 0) {
251
+ throw new Error("portainerEndpointId is required for portainer_ephemeral CI runner");
252
+ }
253
+ const auth = await this.resolvePortainerAuth(params.pipeline.portainerInstanceId);
254
+ if (!auth) {
255
+ throw new Error("Active Portainer instance not found for ephemeral CI runner");
256
+ }
257
+ const headers = {
258
+ "Content-Type": "application/json",
259
+ ...auth.apiKey ? { "X-API-Key": auth.apiKey } : {}
260
+ };
261
+ const envArray = Object.entries(envMap).map(([k, v]) => `${k}=${v}`);
262
+ const createResp = await this.fetchImpl(
263
+ `${auth.baseUrl}/api/endpoints/${endpointId}/docker/containers/create?name=${encodeURIComponent(containerName)}`,
264
+ {
265
+ method: "POST",
266
+ headers,
267
+ body: JSON.stringify({
268
+ Image: image,
269
+ ...cmdString ? { Cmd: ["sh", "-lc", cmdString] } : {},
270
+ Env: envArray,
271
+ Labels: {
272
+ "nocobase.workflow-ci": "true",
273
+ "nocobase.workflow-ci.gate-run": String(params.gateRun.id),
274
+ "nocobase.workflow-ci.test-run": String(params.testRunId),
275
+ "nocobase.workflow-ci.deadline": String(deadlineMs)
276
+ },
277
+ HostConfig: {
278
+ SecurityOpt: ["no-new-privileges:true"],
279
+ ...params.pipeline.runnerNetwork ? { NetworkMode: params.pipeline.runnerNetwork } : {}
280
+ }
281
+ }),
282
+ signal: params.signal
283
+ }
284
+ );
285
+ if (!createResp.ok) {
286
+ throw new Error(`Portainer Docker create container failed with HTTP ${createResp.status}`);
287
+ }
288
+ const createdPayload = await createResp.json();
289
+ const containerId = String(createdPayload.Id || containerName);
290
+ const startResp = await this.fetchImpl(
291
+ `${auth.baseUrl}/api/endpoints/${endpointId}/docker/containers/${encodeURIComponent(containerId)}/start`,
292
+ {
293
+ method: "POST",
294
+ headers,
295
+ signal: params.signal
296
+ }
297
+ );
298
+ if (!startResp.ok && startResp.status !== 304) {
299
+ await this.cleanupContainer(params.pipeline, containerId).catch(() => false);
300
+ throw new Error(`Portainer Docker start container failed with HTTP ${startResp.status}`);
301
+ }
302
+ return {
303
+ launched: true,
304
+ backend: "portainer_ephemeral",
305
+ containerId,
306
+ containerName,
307
+ logs: [
308
+ `Launched one-shot Portainer container "${containerName}" (${containerId.slice(
309
+ 0,
310
+ 12
311
+ )}) on endpoint #${endpointId}`
312
+ ]
313
+ };
314
+ }
315
+ async inspectRunnerContainer(pipeline, containerId, signal) {
316
+ var _a;
317
+ if (!containerId) return { settled: false };
318
+ if (pipeline.runnerBackend === "cluster_ephemeral") {
319
+ const clusterPlugin = this.app.pm.get("plugin-cluster-manager") || this.app.pm.get("cluster-manager");
320
+ if (typeof ((_a = clusterPlugin == null ? void 0 : clusterPlugin.orchestrator) == null ? void 0 : _a.inspectOneShotRunner) === "function") {
321
+ const res = await clusterPlugin.orchestrator.inspectOneShotRunner(containerId);
322
+ return {
323
+ settled: res.settled,
324
+ exitCode: typeof res.exitCode === "number" ? res.exitCode : void 0,
325
+ errorMessage: res.errorMessage
326
+ };
327
+ }
328
+ return { settled: false };
329
+ }
330
+ return this.inspectPortainerContainer(pipeline, containerId, signal);
331
+ }
332
+ async inspectPortainerContainer(pipeline, containerId, signal) {
333
+ const endpointId = Number(pipeline.portainerEndpointId || 0);
334
+ if (!endpointId || !containerId) return { settled: false };
335
+ const auth = await this.resolvePortainerAuth(pipeline.portainerInstanceId);
336
+ if (!auth) return { settled: false };
337
+ const headers = {
338
+ ...auth.apiKey ? { "X-API-Key": auth.apiKey } : {}
339
+ };
340
+ const inspectResp = await this.fetchImpl(
341
+ `${auth.baseUrl}/api/endpoints/${endpointId}/docker/containers/${encodeURIComponent(containerId)}/json`,
342
+ { method: "GET", headers, signal }
343
+ );
344
+ if (!inspectResp.ok) {
345
+ return { settled: false };
346
+ }
347
+ const detail = await inspectResp.json();
348
+ const state = detail.State;
349
+ if (!state || state.Running || state.Status === "created" || state.Status === "restarting") {
350
+ return { settled: false };
351
+ }
352
+ const exitCode = typeof state.ExitCode === "number" ? state.ExitCode : 1;
353
+ return {
354
+ settled: true,
355
+ exitCode,
356
+ ...exitCode !== 0 ? { errorMessage: state.Error || `Ephemeral CI container exited with non-zero code ${exitCode}` } : {}
357
+ };
358
+ }
359
+ async readContainerLogs(pipeline, containerId, tail = 200) {
360
+ var _a, _b;
361
+ if (!containerId) return null;
362
+ if (pipeline.runnerBackend === "cluster_ephemeral") {
363
+ const clusterPlugin = this.app.pm.get("plugin-cluster-manager") || this.app.pm.get("cluster-manager");
364
+ if (typeof ((_a = clusterPlugin == null ? void 0 : clusterPlugin.orchestrator) == null ? void 0 : _a.readOneShotLogs) === "function") {
365
+ return await clusterPlugin.orchestrator.readOneShotLogs(containerId, tail).catch(() => null);
366
+ }
367
+ if (typeof ((_b = clusterPlugin == null ? void 0 : clusterPlugin.orchestrator) == null ? void 0 : _b.getLogs) === "function") {
368
+ return await clusterPlugin.orchestrator.getLogs(containerId, tail).catch(() => null);
369
+ }
370
+ return null;
371
+ }
372
+ const endpointId = Number(pipeline.portainerEndpointId || 0);
373
+ if (!endpointId) return null;
374
+ const auth = await this.resolvePortainerAuth(pipeline.portainerInstanceId);
375
+ if (!auth) return null;
376
+ try {
377
+ const resp = await this.fetchImpl(
378
+ `${auth.baseUrl}/api/endpoints/${endpointId}/docker/containers/${encodeURIComponent(
379
+ containerId
380
+ )}/logs?stdout=1&stderr=1&tail=${Math.max(10, Math.min(1e3, tail))}`,
381
+ {
382
+ method: "GET",
383
+ headers: auth.apiKey ? { "X-API-Key": auth.apiKey } : {}
384
+ }
385
+ );
386
+ if (!resp.ok) return null;
387
+ const arrBuf = await resp.arrayBuffer();
388
+ return demuxDockerLogs(Buffer.from(arrBuf)).trim() || null;
389
+ } catch {
390
+ return null;
391
+ }
392
+ }
393
+ async cleanupContainer(pipeline, containerId) {
394
+ var _a, _b;
395
+ if (!containerId) return true;
396
+ if (pipeline.runnerBackend === "cluster_ephemeral") {
397
+ const clusterPlugin = this.app.pm.get("plugin-cluster-manager") || this.app.pm.get("cluster-manager");
398
+ if (typeof ((_a = clusterPlugin == null ? void 0 : clusterPlugin.orchestrator) == null ? void 0 : _a.removeOneShotRunner) === "function") {
399
+ return await clusterPlugin.orchestrator.removeOneShotRunner(containerId).catch(() => false);
400
+ }
401
+ if (typeof ((_b = clusterPlugin == null ? void 0 : clusterPlugin.orchestrator) == null ? void 0 : _b.removeContainer) === "function") {
402
+ try {
403
+ await clusterPlugin.orchestrator.removeContainer(containerId);
404
+ return true;
405
+ } catch {
406
+ return false;
407
+ }
408
+ }
409
+ return false;
410
+ }
411
+ const endpointId = Number(pipeline.portainerEndpointId || 0);
412
+ if (!endpointId) return false;
413
+ const auth = await this.resolvePortainerAuth(pipeline.portainerInstanceId);
414
+ if (!auth) return false;
415
+ try {
416
+ const resp = await this.fetchImpl(
417
+ `${auth.baseUrl}/api/endpoints/${endpointId}/docker/containers/${encodeURIComponent(
418
+ containerId
419
+ )}?force=true&v=true`,
420
+ {
421
+ method: "DELETE",
422
+ headers: auth.apiKey ? { "X-API-Key": auth.apiKey } : {}
423
+ }
424
+ );
425
+ return resp.ok || resp.status === 404;
426
+ } catch {
427
+ return false;
428
+ }
429
+ }
430
+ async fetchEndpointDockerInfo(auth, endpointId, signal) {
431
+ try {
432
+ const resp = await this.fetchImpl(`${auth.baseUrl}/api/endpoints/${endpointId}/docker/info`, {
433
+ method: "GET",
434
+ headers: auth.apiKey ? { "X-API-Key": auth.apiKey } : {},
435
+ signal
436
+ });
437
+ if (!resp.ok) return null;
438
+ const raw = await resp.json();
439
+ const id = String((raw == null ? void 0 : raw.ID) ?? "").trim();
440
+ if (!id) return null;
441
+ return {
442
+ id,
443
+ architecture: raw == null ? void 0 : raw.Architecture,
444
+ osType: raw == null ? void 0 : raw.OSType
445
+ };
446
+ } catch {
447
+ return null;
448
+ }
449
+ }
450
+ async listRuntimeStackContainers(params) {
451
+ const filters = encodeURIComponent(JSON.stringify({ label: [`com.docker.compose.project=${params.stackName}`] }));
452
+ const resp = await this.fetchImpl(
453
+ `${params.auth.baseUrl}/api/endpoints/${params.endpointId}/docker/containers/json?all=1&filters=${filters}`,
454
+ {
455
+ method: "GET",
456
+ headers: params.auth.apiKey ? { "X-API-Key": params.auth.apiKey } : {},
457
+ signal: params.signal
458
+ }
459
+ );
460
+ if (!resp.ok) {
461
+ throw new Error(`Unable to inspect containers of stack "${params.stackName}" (HTTP ${resp.status})`);
462
+ }
463
+ const rawList = await resp.json();
464
+ if (!Array.isArray(rawList)) return [];
465
+ return rawList.map((c) => {
466
+ var _a;
467
+ const state = String(c.State ?? "").toLowerCase();
468
+ const status = String(c.Status ?? "");
469
+ const unhealthyOrStarting = /\((?:unhealthy|health:\s*starting)\)/i.test(status) || state === "restarting" || state === "dead";
470
+ const firstName = Array.isArray(c.Names) && c.Names[0] ? c.Names[0].replace(/^\/+/, "") : String(c.Id ?? "");
471
+ return {
472
+ id: String(c.Id ?? ""),
473
+ name: firstName,
474
+ serviceName: (_a = c.Labels) == null ? void 0 : _a["com.docker.compose.service"],
475
+ image: String(c.Image ?? ""),
476
+ imageId: String(c.ImageID ?? ""),
477
+ state,
478
+ status,
479
+ healthy: state === "running" && !unhealthyOrStarting
480
+ };
481
+ });
482
+ }
483
+ async waitAndVerifyStackHealthAndImages(params) {
484
+ var _a;
485
+ const deadline = Date.now() + this.rolloutMaxWaitMs;
486
+ let lastReason = `Timed out waiting for stack "${params.stackName}" containers`;
487
+ while (Date.now() <= deadline) {
488
+ if ((_a = params.signal) == null ? void 0 : _a.aborted) {
489
+ return { ok: false, verifiedAppImages: [], reason: "Rollout verification aborted" };
490
+ }
491
+ let containers = [];
492
+ try {
493
+ containers = await this.listRuntimeStackContainers({
494
+ auth: params.auth,
495
+ endpointId: params.endpointId,
496
+ stackName: params.stackName,
497
+ signal: params.signal
498
+ });
499
+ } catch (error) {
500
+ lastReason = error instanceof Error ? error.message : String(error);
501
+ return { ok: false, verifiedAppImages: [], reason: lastReason };
502
+ }
503
+ if (containers.length < params.desiredReplicas) {
504
+ lastReason = `Insufficient replicas on "${params.stackName}": found ${containers.length}/${params.desiredReplicas}`;
505
+ } else if (containers.some((c) => !c.healthy)) {
506
+ const bad = containers.filter((c) => !c.healthy).map((c) => `${c.name}(${c.state}:${c.status})`);
507
+ lastReason = `Unhealthy or restarting container(s) on "${params.stackName}": ${bad.join(", ")}`;
508
+ } else {
509
+ let imageMismatch = null;
510
+ for (const exp of params.expectedImages) {
511
+ const matchingContainers = exp.serviceName ? containers.filter((c) => c.serviceName === exp.serviceName) : containers;
512
+ if (matchingContainers.length === 0) {
513
+ imageMismatch = `Expected service "${exp.serviceName || "app"}" has 0 running containers`;
514
+ break;
515
+ }
516
+ for (const mc of matchingContainers) {
517
+ if (exp.imageId && mc.imageId && mc.imageId !== exp.imageId) {
518
+ imageMismatch = `Container "${mc.name}" is running imageId "${mc.imageId}", expected "${exp.imageId}"`;
519
+ break;
520
+ }
521
+ if (exp.repoDigest && mc.image.includes("@sha256:") && mc.image !== exp.repoDigest) {
522
+ imageMismatch = `Container "${mc.name}" is running digest "${mc.image}", expected "${exp.repoDigest}"`;
523
+ break;
524
+ }
525
+ if (!exp.imageId && exp.tag && !mc.image.endsWith(`:${exp.tag}`) && !mc.image.includes("@sha256:")) {
526
+ imageMismatch = `Container "${mc.name}" is running image "${mc.image}", expected tag ":${exp.tag}"`;
527
+ break;
528
+ }
529
+ }
530
+ if (imageMismatch) break;
531
+ }
532
+ if (!imageMismatch) {
533
+ return {
534
+ ok: true,
535
+ verifiedAppImages: containers.map((c) => ({
536
+ containerId: c.id.slice(0, 12),
537
+ containerName: c.name,
538
+ ...c.serviceName ? { serviceName: c.serviceName } : {},
539
+ imageRef: c.image,
540
+ imageId: c.imageId,
541
+ healthy: c.healthy
542
+ }))
543
+ };
544
+ }
545
+ lastReason = imageMismatch;
546
+ }
547
+ if (Date.now() + this.rolloutPollIntervalMs > deadline) {
548
+ break;
549
+ }
550
+ await new Promise((resolve) => {
551
+ setTimeout(resolve, this.rolloutPollIntervalMs);
552
+ });
553
+ }
554
+ return { ok: false, verifiedAppImages: [], reason: lastReason };
555
+ }
556
+ async verifySnapshotImagesExist(auth, endpointId, snapshot, signal) {
557
+ if (snapshot.verifiedAppImages.length === 0) return false;
558
+ try {
559
+ const resp = await this.fetchImpl(`${auth.baseUrl}/api/endpoints/${endpointId}/docker/images/json`, {
560
+ method: "GET",
561
+ headers: auth.apiKey ? { "X-API-Key": auth.apiKey } : {},
562
+ signal
563
+ });
564
+ if (!resp.ok) {
565
+ return snapshot.verifiedAppImages.every((img) => img.imageRef.includes("@sha256:") || Boolean(img.repoDigest));
566
+ }
567
+ const images = await resp.json();
568
+ if (!Array.isArray(images)) return false;
569
+ return snapshot.verifiedAppImages.every((reqImg) => {
570
+ if (reqImg.imageRef.includes("@sha256:") || reqImg.repoDigest) return true;
571
+ return images.some(
572
+ (item) => reqImg.imageId && item.Id === reqImg.imageId || Array.isArray(item.RepoTags) && item.RepoTags.includes(reqImg.imageRef)
573
+ );
574
+ });
575
+ } catch {
576
+ return false;
577
+ }
578
+ }
579
+ async promoteRuntimeDeployStack(params) {
580
+ var _a, _b, _c, _d, _e;
581
+ if (params.pipeline.promotionHalted) {
582
+ return {
583
+ promoted: false,
584
+ deployOutcome: "blocked",
585
+ detail: `Production promotion is halted on pipeline "${params.pipeline.key}": ${params.pipeline.promotionHaltReason || "Ops intervention required from previous failed rollout"}`
586
+ };
587
+ }
588
+ let instanceId = params.pipeline.deployInstanceId ?? params.pipeline.portainerInstanceId ?? null;
589
+ let endpointId = params.pipeline.deployEndpointId ?? params.pipeline.portainerEndpointId ?? null;
590
+ let stackId = params.pipeline.deployStackId ?? null;
591
+ if ((!stackId || !endpointId) && params.pipeline.portainerPipelineId && this.hasCollection(import_constants.PORTAINER_PIPELINES_COLLECTION)) {
592
+ const linked = await this.app.db.getRepository(import_constants.PORTAINER_PIPELINES_COLLECTION).findOne({ filterByTk: params.pipeline.portainerPipelineId });
593
+ if (linked) {
594
+ stackId = stackId ?? (linked.get("deployStackId") != null ? Number(linked.get("deployStackId")) : null);
595
+ endpointId = endpointId ?? (linked.get("deployEndpointId") != null ? Number(linked.get("deployEndpointId")) : null);
596
+ instanceId = instanceId ?? (linked.get("deployInstanceId") != null ? Number(linked.get("deployInstanceId")) : null);
597
+ }
598
+ }
599
+ if (!stackId || !endpointId) {
600
+ return {
601
+ promoted: false,
602
+ deployOutcome: "blocked",
603
+ detail: "Quality Gate blocked promotion: deployStackId and deployEndpointId are required when deploy gate is enabled"
604
+ };
605
+ }
606
+ const auth = await this.resolvePortainerAuth(instanceId);
607
+ if (!auth) {
608
+ return {
609
+ promoted: false,
610
+ deployOutcome: "failed",
611
+ stackId,
612
+ endpointId,
613
+ instanceId,
614
+ detail: "Portainer instance unavailable for runtime stack promotion"
615
+ };
616
+ }
617
+ const headers = {
618
+ "Content-Type": "application/json",
619
+ ...auth.apiKey ? { "X-API-Key": auth.apiKey } : {}
620
+ };
621
+ const prodDaemonInfo = await this.fetchEndpointDockerInfo(auth, endpointId, params.signal);
622
+ const artifacts = ((_a = params.buildProvenance) == null ? void 0 : _a.serviceArtifacts) ?? [];
623
+ const hasAllRegistryDigests = artifacts.length > 0 && artifacts.every((a) => Boolean(a.repoDigest));
624
+ const isSameEngineLocalMode = !hasAllRegistryDigests;
625
+ if (isSameEngineLocalMode && ((_b = params.buildProvenance) == null ? void 0 : _b.dockerDaemonId)) {
626
+ if (!(prodDaemonInfo == null ? void 0 : prodDaemonInfo.id) || prodDaemonInfo.id !== params.buildProvenance.dockerDaemonId) {
627
+ return {
628
+ promoted: false,
629
+ deployOutcome: "blocked",
630
+ stackId,
631
+ endpointId,
632
+ instanceId,
633
+ detail: `DOCKER_ENGINE_MISMATCH: Build ran on Docker Engine "${params.buildProvenance.dockerDaemonId}" without registry digests, but production endpoint #${endpointId} is "${(prodDaemonInfo == null ? void 0 : prodDaemonInfo.id) || "unknown"}"`
634
+ };
635
+ }
636
+ }
637
+ const stackResp = await this.fetchImpl(`${auth.baseUrl}/api/stacks/${stackId}`, {
638
+ method: "GET",
639
+ headers,
640
+ signal: params.signal
641
+ });
642
+ if (!stackResp.ok) {
643
+ return {
644
+ promoted: false,
645
+ deployOutcome: "failed",
646
+ stackId,
647
+ endpointId,
648
+ instanceId,
649
+ detail: `Failed to read Portainer runtime stack #${stackId} (HTTP ${stackResp.status})`
650
+ };
651
+ }
652
+ const stackDetail = await stackResp.json();
653
+ const stackName = stackDetail.Name || String(stackId);
654
+ const fileResp = await this.fetchImpl(`${auth.baseUrl}/api/stacks/${stackId}/file`, {
655
+ method: "GET",
656
+ headers,
657
+ signal: params.signal
658
+ });
659
+ const filePayload = fileResp.ok ? await fileResp.json() : { StackFileContent: "" };
660
+ const currentComposeContent = filePayload.StackFileContent ?? "";
661
+ const currentRunning = await this.listRuntimeStackContainers({
662
+ auth,
663
+ endpointId,
664
+ stackName,
665
+ signal: params.signal
666
+ }).catch(() => []);
667
+ const healthyCurrent = currentRunning.filter((c) => c.healthy);
668
+ const previousGoodSnapshot = healthyCurrent.length > 0 && currentComposeContent.trim() ? {
669
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
670
+ stackId,
671
+ stackName,
672
+ endpointId,
673
+ instanceId,
674
+ stackFileContent: currentComposeContent,
675
+ env: (stackDetail.Env ?? []).filter((p) => Boolean(p == null ? void 0 : p.name)).map((p) => ({ name: p.name, value: String(p.value ?? "") })),
676
+ desiredReplicas: healthyCurrent.length,
677
+ dockerDaemonId: (prodDaemonInfo == null ? void 0 : prodDaemonInfo.id) ?? null,
678
+ verifiedAppImages: healthyCurrent.map((c) => ({
679
+ containerId: c.id.slice(0, 12),
680
+ containerName: c.name,
681
+ ...c.serviceName ? { serviceName: c.serviceName } : {},
682
+ imageRef: c.image,
683
+ imageId: c.imageId,
684
+ healthy: true
685
+ }))
686
+ } : params.pipeline.lastKnownGoodSnapshot ?? null;
687
+ const desiredReplicas = Math.max(1, healthyCurrent.length || (previousGoodSnapshot == null ? void 0 : previousGoodSnapshot.desiredReplicas) || 1);
688
+ const resolvedTag = ((_c = params.buildProvenance) == null ? void 0 : _c.resolvedImageTag) || params.gateRun.commitSha.slice(0, 7);
689
+ const tagEnvName = ((_d = params.buildProvenance) == null ? void 0 : _d.imageTagEnvName) || "VERIFIED_IMAGE_TAG";
690
+ const envMap = /* @__PURE__ */ new Map();
691
+ for (const pair of stackDetail.Env ?? []) {
692
+ if (pair == null ? void 0 : pair.name) envMap.set(pair.name, String(pair.value ?? ""));
693
+ }
694
+ envMap.set("GIT_COMMIT_SHA", params.gateRun.commitSha);
695
+ envMap.set("GIT_SHORT_SHA", resolvedTag);
696
+ envMap.set("GIT_BRANCH", params.gateRun.branch);
697
+ envMap.set("VERIFIED_IMAGE_TAG", resolvedTag);
698
+ if (tagEnvName && /^[A-Za-z_][A-Za-z0-9_]*$/.test(tagEnvName)) {
699
+ envMap.set(tagEnvName, resolvedTag);
700
+ }
701
+ let nextComposeContent = currentComposeContent;
702
+ if (hasAllRegistryDigests) {
703
+ const digestByRepo = /* @__PURE__ */ new Map();
704
+ for (const art of artifacts) {
705
+ if (art.repository && art.repoDigest) {
706
+ digestByRepo.set(art.repository, art.repoDigest);
707
+ }
708
+ }
709
+ nextComposeContent = pinComposeImageDigests(nextComposeContent, digestByRepo);
710
+ } else if (artifacts.length > 0) {
711
+ nextComposeContent = injectLocalPullPolicyInCompose(
712
+ nextComposeContent,
713
+ artifacts.map((a) => a.repository).filter(Boolean)
714
+ );
715
+ }
716
+ let putErrorMsg = null;
717
+ try {
718
+ const putResp = await this.fetchImpl(`${auth.baseUrl}/api/stacks/${stackId}?endpointId=${endpointId}`, {
719
+ method: "PUT",
720
+ headers,
721
+ body: JSON.stringify({
722
+ StackFileContent: nextComposeContent,
723
+ Env: [...envMap.entries()].map(([name, value]) => ({ name, value })),
724
+ Prune: false,
725
+ PullImage: hasAllRegistryDigests
726
+ }),
727
+ signal: params.signal
728
+ });
729
+ if (!putResp.ok) {
730
+ putErrorMsg = `Portainer stack update HTTP ${putResp.status}`;
731
+ }
732
+ } catch (error) {
733
+ putErrorMsg = `Portainer PUT connection interrupted (${error instanceof Error ? error.message : String(error)})`;
734
+ }
735
+ const expectedImages = artifacts.length > 0 ? artifacts.map((a) => ({
736
+ serviceName: a.serviceName,
737
+ imageRef: a.repoDigest || a.imageRef,
738
+ imageId: a.imageConfigId ?? null,
739
+ repoDigest: a.repoDigest ?? null,
740
+ tag: a.tag || resolvedTag
741
+ })) : [{ tag: resolvedTag }];
742
+ const verification = await this.waitAndVerifyStackHealthAndImages({
743
+ auth,
744
+ endpointId,
745
+ stackName,
746
+ desiredReplicas,
747
+ expectedImages,
748
+ signal: params.signal
749
+ });
750
+ if (verification.ok) {
751
+ const updatedGoodSnapshot = {
752
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
753
+ stackId,
754
+ stackName,
755
+ endpointId,
756
+ instanceId,
757
+ stackFileContent: nextComposeContent,
758
+ env: [...envMap.entries()].map(([name, value]) => ({ name, value })),
759
+ desiredReplicas: verification.verifiedAppImages.length,
760
+ verifiedImageTag: resolvedTag,
761
+ dockerDaemonId: (prodDaemonInfo == null ? void 0 : prodDaemonInfo.id) ?? null,
762
+ verifiedAppImages: verification.verifiedAppImages
763
+ };
764
+ return {
765
+ promoted: true,
766
+ deployOutcome: "deployed",
767
+ stackId,
768
+ stackName,
769
+ endpointId,
770
+ instanceId,
771
+ detail: `Promoted & verified ${verification.verifiedAppImages.length} healthy container(s) on stack "${stackName}" (tag=${resolvedTag})`,
772
+ verifiedAppImages: verification.verifiedAppImages,
773
+ previousGoodSnapshot,
774
+ updatedGoodSnapshot
775
+ };
776
+ }
777
+ const failureReason = [putErrorMsg, verification.reason].filter(Boolean).join(" \u2014 ");
778
+ const dbBackwardCompatible = params.pipeline.dbBackwardCompatible !== false;
779
+ const hasRollbackSnapshot = Boolean((_e = previousGoodSnapshot == null ? void 0 : previousGoodSnapshot.stackFileContent) == null ? void 0 : _e.trim()) && Boolean(previousGoodSnapshot && previousGoodSnapshot.verifiedAppImages.length > 0);
780
+ const snapshotImagesAvailable = dbBackwardCompatible && previousGoodSnapshot ? await this.verifySnapshotImagesExist(auth, endpointId, previousGoodSnapshot, params.signal) : false;
781
+ if (!dbBackwardCompatible || !hasRollbackSnapshot || !snapshotImagesAvailable || !previousGoodSnapshot) {
782
+ const ineligibleReason = !dbBackwardCompatible ? "dbBackwardCompatible is false (refusing automatic rollback over non-backward-compatible schema)" : !hasRollbackSnapshot ? "No previous lastKnownGoodSnapshot recorded for this production stack" : "Previous lastKnownGoodSnapshot image is no longer present on the Docker engine/registry";
783
+ const rollbackRecord2 = {
784
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
785
+ reason: failureReason,
786
+ eligible: false,
787
+ dbBackwardCompatible,
788
+ restoredFromCapturedAt: (previousGoodSnapshot == null ? void 0 : previousGoodSnapshot.capturedAt) ?? null,
789
+ rollbackSucceeded: false,
790
+ detail: `Rollout failed (${failureReason}); auto-rollback skipped: ${ineligibleReason}`
791
+ };
792
+ return {
793
+ promoted: false,
794
+ deployOutcome: "ops_intervention_required",
795
+ stackId,
796
+ stackName,
797
+ endpointId,
798
+ instanceId,
799
+ detail: rollbackRecord2.detail,
800
+ previousGoodSnapshot,
801
+ rollbackRecord: rollbackRecord2,
802
+ haltPromotion: true,
803
+ haltReason: rollbackRecord2.detail
804
+ };
805
+ }
806
+ const lkgHasDigests = previousGoodSnapshot.verifiedAppImages.every(
807
+ (img) => img.imageRef.includes("@sha256:") || Boolean(img.repoDigest)
808
+ );
809
+ let rollbackPutOk = false;
810
+ try {
811
+ const rbResp = await this.fetchImpl(`${auth.baseUrl}/api/stacks/${stackId}?endpointId=${endpointId}`, {
812
+ method: "PUT",
813
+ headers,
814
+ body: JSON.stringify({
815
+ StackFileContent: previousGoodSnapshot.stackFileContent,
816
+ Env: previousGoodSnapshot.env,
817
+ Prune: false,
818
+ PullImage: lkgHasDigests
819
+ }),
820
+ signal: params.signal
821
+ });
822
+ rollbackPutOk = rbResp.ok;
823
+ } catch {
824
+ rollbackPutOk = false;
825
+ }
826
+ const rbVerify = rollbackPutOk ? await this.waitAndVerifyStackHealthAndImages({
827
+ auth,
828
+ endpointId,
829
+ stackName,
830
+ desiredReplicas: previousGoodSnapshot.desiredReplicas,
831
+ expectedImages: previousGoodSnapshot.verifiedAppImages.map((img) => ({
832
+ serviceName: img.serviceName,
833
+ imageRef: img.imageRef,
834
+ imageId: img.imageId || null,
835
+ repoDigest: img.repoDigest ?? null
836
+ })),
837
+ signal: params.signal
838
+ }) : { ok: false, verifiedAppImages: [], reason: "Rollback PUT request failed" };
839
+ if (rbVerify.ok) {
840
+ const verifiedAt = (/* @__PURE__ */ new Date()).toISOString();
841
+ const rollbackRecord2 = {
842
+ triggeredAt: verifiedAt,
843
+ reason: failureReason,
844
+ eligible: true,
845
+ dbBackwardCompatible,
846
+ restoredFromCapturedAt: previousGoodSnapshot.capturedAt,
847
+ rollbackSucceeded: true,
848
+ rollbackVerifiedAt: verifiedAt,
849
+ detail: `Rollout failed (${failureReason}); automatically rolled back "${stackName}" to lastKnownGood (${previousGoodSnapshot.capturedAt}) and verified ${rbVerify.verifiedAppImages.length} healthy replica(s)`
850
+ };
851
+ return {
852
+ promoted: false,
853
+ deployOutcome: "rolled_back",
854
+ stackId,
855
+ stackName,
856
+ endpointId,
857
+ instanceId,
858
+ detail: rollbackRecord2.detail,
859
+ verifiedAppImages: rbVerify.verifiedAppImages,
860
+ previousGoodSnapshot,
861
+ rollbackRecord: rollbackRecord2
862
+ };
863
+ }
864
+ const rollbackRecord = {
865
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
866
+ reason: failureReason,
867
+ eligible: true,
868
+ dbBackwardCompatible,
869
+ restoredFromCapturedAt: previousGoodSnapshot.capturedAt,
870
+ rollbackSucceeded: false,
871
+ detail: `Rollout failed (${failureReason}) AND automatic rollback verification failed (${rbVerify.reason}); halting further promotions`
872
+ };
873
+ return {
874
+ promoted: false,
875
+ deployOutcome: "ops_intervention_required",
876
+ stackId,
877
+ stackName,
878
+ endpointId,
879
+ instanceId,
880
+ detail: rollbackRecord.detail,
881
+ previousGoodSnapshot,
882
+ rollbackRecord,
883
+ haltPromotion: true,
884
+ haltReason: rollbackRecord.detail
885
+ };
886
+ }
887
+ }
888
+ // Annotate the CommonJS export names for ESM import in node:
889
+ 0 && (module.exports = {
890
+ EphemeralContainerService
891
+ });