plugin-workflow-portainer 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/LICENSE +176 -0
  2. package/README.md +31 -3
  3. package/client-v2.js +1 -0
  4. package/client.js +1 -0
  5. package/dist/client/127.5012da93825a6e5c.js +10 -0
  6. package/dist/client/57.ace9538136438718.js +10 -0
  7. package/dist/client/65.ec4a55173511c06d.js +10 -0
  8. package/dist/client/660.546c702d1ddf7eff.js +10 -0
  9. package/dist/client/index.js +10 -0
  10. package/dist/client-v2/127.0ec4dce7b13750e9.js +10 -0
  11. package/dist/client-v2/57.e7cfc50fb651ac14.js +10 -0
  12. package/dist/client-v2/65.9c745ea32ac96e98.js +10 -0
  13. package/dist/client-v2/660.29ae3c3b4040039d.js +10 -0
  14. package/dist/client-v2/index.js +10 -0
  15. package/dist/externalVersion.js +20 -0
  16. package/dist/index.js +48 -0
  17. package/dist/locale/en-US.json +151 -0
  18. package/dist/locale/vi-VN.json +151 -0
  19. package/dist/locale/zh-CN.json +151 -0
  20. package/dist/node_modules/joi/dist/joi-browser.min.js +1 -0
  21. package/dist/node_modules/joi/lib/annotate.js +175 -0
  22. package/dist/node_modules/joi/lib/base.js +1069 -0
  23. package/dist/node_modules/joi/lib/cache.js +143 -0
  24. package/dist/node_modules/joi/lib/common.js +216 -0
  25. package/dist/node_modules/joi/lib/compile.js +283 -0
  26. package/dist/node_modules/joi/lib/errors.js +271 -0
  27. package/dist/node_modules/joi/lib/extend.js +312 -0
  28. package/dist/node_modules/joi/lib/index.d.ts +2365 -0
  29. package/dist/node_modules/joi/lib/index.js +1 -0
  30. package/dist/node_modules/joi/lib/manifest.js +476 -0
  31. package/dist/node_modules/joi/lib/messages.js +207 -0
  32. package/dist/node_modules/joi/lib/modify.js +267 -0
  33. package/dist/node_modules/joi/lib/ref.js +414 -0
  34. package/dist/node_modules/joi/lib/schemas.js +302 -0
  35. package/dist/node_modules/joi/lib/state.js +166 -0
  36. package/dist/node_modules/joi/lib/template.js +463 -0
  37. package/dist/node_modules/joi/lib/trace.js +346 -0
  38. package/dist/node_modules/joi/lib/types/alternatives.js +364 -0
  39. package/dist/node_modules/joi/lib/types/any.js +174 -0
  40. package/dist/node_modules/joi/lib/types/array.js +809 -0
  41. package/dist/node_modules/joi/lib/types/binary.js +100 -0
  42. package/dist/node_modules/joi/lib/types/boolean.js +150 -0
  43. package/dist/node_modules/joi/lib/types/date.js +233 -0
  44. package/dist/node_modules/joi/lib/types/function.js +93 -0
  45. package/dist/node_modules/joi/lib/types/keys.js +1084 -0
  46. package/dist/node_modules/joi/lib/types/link.js +184 -0
  47. package/dist/node_modules/joi/lib/types/number.js +363 -0
  48. package/dist/node_modules/joi/lib/types/object.js +22 -0
  49. package/dist/node_modules/joi/lib/types/string.js +850 -0
  50. package/dist/node_modules/joi/lib/types/symbol.js +102 -0
  51. package/dist/node_modules/joi/lib/validator.js +750 -0
  52. package/dist/node_modules/joi/lib/values.js +263 -0
  53. package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.d.ts +60 -0
  54. package/dist/node_modules/joi/node_modules/@hapi/topo/lib/index.js +225 -0
  55. package/dist/node_modules/joi/node_modules/@hapi/topo/package.json +30 -0
  56. package/dist/node_modules/joi/package.json +1 -0
  57. package/dist/server/actions/portainer.js +192 -0
  58. package/dist/server/collections/portainer-instances.js +54 -0
  59. package/dist/server/index.js +54 -0
  60. package/dist/server/instructions/PortainerStackControlInstruction.js +156 -0
  61. package/dist/server/instructions/PortainerStackRedeployInstruction.js +254 -0
  62. package/dist/server/instructions/helpers.js +211 -0
  63. package/dist/server/plugin.js +170 -0
  64. package/dist/server/services/PortainerClient.js +497 -0
  65. package/dist/shared/collection.js +57 -0
  66. package/dist/shared/constants.js +66 -0
  67. package/dist/shared/env.js +221 -0
  68. package/dist/shared/types.js +24 -0
  69. package/package.json +50 -4
  70. package/server.js +1 -0
  71. package/src/client/index.tsx +50 -0
  72. package/src/client/instructions.tsx +76 -0
  73. package/src/client-v2/__tests__/workflow-registration.test.tsx +132 -0
  74. package/src/client-v2/components/ControlFieldset.tsx +46 -0
  75. package/src/client-v2/components/PortainerEnvEditor.tsx +223 -0
  76. package/src/client-v2/components/PortainerSettingsPage.tsx +671 -0
  77. package/src/client-v2/components/PortainerTargetFields.tsx +317 -0
  78. package/src/client-v2/components/RedeployFieldset.tsx +123 -0
  79. package/src/client-v2/index.tsx +50 -0
  80. package/src/client-v2/instructions.tsx +162 -0
  81. package/src/client-v2/locale.ts +24 -0
  82. package/src/index.ts +11 -0
  83. package/src/locale/en-US.json +151 -0
  84. package/src/locale/vi-VN.json +151 -0
  85. package/src/locale/zh-CN.json +151 -0
  86. package/src/server/__tests__/portainer-workflow.test.ts +455 -0
  87. package/src/server/actions/portainer.ts +196 -0
  88. package/src/server/collections/portainer-instances.ts +34 -0
  89. package/src/server/index.ts +13 -0
  90. package/src/server/instructions/PortainerStackControlInstruction.ts +139 -0
  91. package/src/server/instructions/PortainerStackRedeployInstruction.ts +255 -0
  92. package/src/server/instructions/helpers.ts +237 -0
  93. package/src/server/plugin.ts +167 -0
  94. package/src/server/services/PortainerClient.ts +589 -0
  95. package/src/shared/collection.ts +32 -0
  96. package/src/shared/constants.ts +25 -0
  97. package/src/shared/env.ts +228 -0
  98. package/src/shared/types.ts +105 -0
@@ -0,0 +1,13 @@
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
+ export { default, PluginWorkflowPortainerServer } from './plugin';
11
+ export * from './services/PortainerClient';
12
+ export * from './instructions/PortainerStackRedeployInstruction';
13
+ export * from './instructions/PortainerStackControlInstruction';
@@ -0,0 +1,139 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import Joi from 'joi';
11
+ import { Instruction, JOB_STATUS, type FlowNodeModel, type JobModel, type Processor } from '@nocobase/plugin-workflow';
12
+ import { buildEffectiveStackEnv } from '../../shared/env';
13
+ import type { PortainerContainerSummary, PortainerStackControlConfig, StackControlAction } from '../../shared/types';
14
+ import { assertPositiveInt, summarizeContainersHealth, toStackDetail } from '../services/PortainerClient';
15
+ import { formatFailureResult, resolvePortainerInstance, runPortainerWorkflowTask } from './helpers';
16
+
17
+ const numOrVar = Joi.alternatives().try(Joi.number(), Joi.string().allow(''), Joi.allow(null));
18
+
19
+ export async function executePortainerControl(
20
+ app: Parameters<typeof resolvePortainerInstance>[0],
21
+ config: PortainerStackControlConfig,
22
+ signal?: AbortSignal,
23
+ ) {
24
+ const startedAt = new Date();
25
+ const instance = await resolvePortainerInstance(app, config.instanceId ?? null);
26
+ const stackId = assertPositiveInt(config.stackId ?? undefined, 'Stack ID');
27
+ const action: StackControlAction = config.action === 'start' || config.action === 'stop' ? config.action : 'inspect';
28
+
29
+ let rawStack = await instance.client.getRawStack(stackId, signal);
30
+ const hasExplicitEndpoint =
31
+ config.endpointId !== null && typeof config.endpointId !== 'undefined' && String(config.endpointId).trim() !== '';
32
+ const endpointId = hasExplicitEndpoint
33
+ ? assertPositiveInt(config.endpointId ?? undefined, 'Environment (Endpoint) ID')
34
+ : assertPositiveInt(rawStack.EndpointId, 'Stack Endpoint ID');
35
+
36
+ if (action === 'start') {
37
+ rawStack = await instance.client.startStack(stackId, endpointId, signal);
38
+ rawStack = await instance.client.waitForStackSettlement(stackId, rawStack, {
39
+ timeoutMs: config.timeoutMs ? Number(config.timeoutMs) : instance.defaultTimeoutMs,
40
+ signal,
41
+ });
42
+ } else if (action === 'stop') {
43
+ rawStack = await instance.client.stopStack(stackId, endpointId, signal);
44
+ rawStack = await instance.client.waitForStackSettlement(stackId, rawStack, {
45
+ timeoutMs: config.timeoutMs ? Number(config.timeoutMs) : instance.defaultTimeoutMs,
46
+ signal,
47
+ });
48
+ }
49
+
50
+ const detail = toStackDetail(rawStack);
51
+ const { maskedEnv } = buildEffectiveStackEnv({
52
+ existingEnv: detail.env,
53
+ strategy: 'merge',
54
+ });
55
+
56
+ let containers: PortainerContainerSummary[] = [];
57
+ try {
58
+ containers = await instance.client.listStackContainers(endpointId, detail.name, signal);
59
+ } catch {
60
+ containers = [];
61
+ }
62
+
63
+ const summary = summarizeContainersHealth(containers);
64
+ const stackStatus = Number(rawStack.Status ?? detail.status ?? 1);
65
+ const healthy =
66
+ action === 'stop' ? summary.runningCount === 0 : containers.length > 0 ? summary.healthy : stackStatus === 1;
67
+
68
+ const finishedAt = new Date();
69
+ return {
70
+ ok: true,
71
+ action,
72
+ instanceId: instance.id,
73
+ instanceName: instance.name,
74
+ endpointId,
75
+ stackId,
76
+ stackName: detail.name,
77
+ stackType: detail.isGitStack ? ('git' as const) : ('compose' as const),
78
+ stackStatus,
79
+ gitReference: detail.gitReference ?? null,
80
+ healthy,
81
+ runningCount: summary.runningCount,
82
+ totalCount: summary.totalCount,
83
+ containers,
84
+ currentEnv: maskedEnv,
85
+ startedAt: startedAt.toISOString(),
86
+ finishedAt: finishedAt.toISOString(),
87
+ durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()),
88
+ };
89
+ }
90
+
91
+ export class PortainerStackControlInstruction extends Instruction {
92
+ configSchema = Joi.object({
93
+ instanceId: numOrVar,
94
+ endpointId: numOrVar,
95
+ stackId: numOrVar,
96
+ action: Joi.string().valid('inspect', 'start', 'stop').default('inspect'),
97
+ timeoutMs: numOrVar,
98
+ ignoreFail: Joi.boolean().default(false),
99
+ }).unknown(true);
100
+
101
+ async run(node: FlowNodeModel, prevJob: JobModel, processor: Processor, options?: { signal?: AbortSignal }) {
102
+ const config = processor.getParsedValue(node.config ?? {}, node.id) as PortainerStackControlConfig;
103
+ return runPortainerWorkflowTask({
104
+ workflow: this.workflow,
105
+ node,
106
+ prevJob,
107
+ processor,
108
+ ignoreFail: config.ignoreFail,
109
+ signal: options?.signal,
110
+ execute: (signal) => executePortainerControl(this.workflow.app, config, signal),
111
+ });
112
+ }
113
+
114
+ async resume(node: FlowNodeModel, job: JobModel) {
115
+ const config = (node.config ?? {}) as PortainerStackControlConfig;
116
+ if (config.ignoreFail) {
117
+ job.set('status', JOB_STATUS.RESOLVED);
118
+ }
119
+ return job;
120
+ }
121
+
122
+ async test(config: PortainerStackControlConfig) {
123
+ const startedAt = new Date();
124
+ try {
125
+ const result = await executePortainerControl(this.workflow.app, config);
126
+ return {
127
+ status: JOB_STATUS.RESOLVED,
128
+ result,
129
+ };
130
+ } catch (error) {
131
+ return {
132
+ status: config.ignoreFail ? JOB_STATUS.RESOLVED : JOB_STATUS.FAILED,
133
+ result: formatFailureResult(error, startedAt),
134
+ };
135
+ }
136
+ }
137
+ }
138
+
139
+ export default PortainerStackControlInstruction;
@@ -0,0 +1,255 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import Joi from 'joi';
11
+ import { Instruction, JOB_STATUS, type FlowNodeModel, type JobModel, type Processor } from '@nocobase/plugin-workflow';
12
+ import { buildEffectiveStackEnv, normalizeGitReference } from '../../shared/env';
13
+ import type { PortainerContainerSummary, PortainerStackRedeployConfig } from '../../shared/types';
14
+ import {
15
+ assertPositiveInt,
16
+ clampTimeoutMs,
17
+ PortainerApiError,
18
+ summarizeContainersHealth,
19
+ toStackDetail,
20
+ type RawPortainerStack,
21
+ } from '../services/PortainerClient';
22
+ import {
23
+ formatFailureResult,
24
+ resolvePortainerInstance,
25
+ runPortainerWorkflowTask,
26
+ type ResolvedPortainerInstance,
27
+ } from './helpers';
28
+
29
+ const numOrVar = Joi.alternatives().try(Joi.number(), Joi.string().allow(''), Joi.allow(null));
30
+
31
+ function resolveGitAuthPayload(stack: RawPortainerStack, instance: ResolvedPortainerInstance) {
32
+ const stackAuth = stack.GitConfig?.Authentication;
33
+ const stackCredId = Number(stackAuth?.GitCredentialID ?? 0);
34
+ const effectiveCredId = stackCredId > 0 ? stackCredId : instance.gitCredentialId;
35
+
36
+ if (effectiveCredId && effectiveCredId > 0) {
37
+ return {
38
+ repositoryAuthentication: true,
39
+ repositoryGitCredentialID: effectiveCredId,
40
+ ...(stackAuth?.Username ? { repositoryUsername: String(stackAuth.Username) } : {}),
41
+ };
42
+ }
43
+
44
+ if (instance.gitAccessToken) {
45
+ return {
46
+ repositoryAuthentication: true,
47
+ repositoryUsername: String(stackAuth?.Username || instance.gitUsername || 'oauth2'),
48
+ repositoryPassword: instance.gitAccessToken,
49
+ };
50
+ }
51
+
52
+ if (stackAuth?.Username) {
53
+ return {
54
+ repositoryAuthentication: true,
55
+ repositoryUsername: String(stackAuth.Username),
56
+ };
57
+ }
58
+
59
+ return {
60
+ repositoryAuthentication: false,
61
+ };
62
+ }
63
+
64
+ export async function executePortainerRedeploy(
65
+ app: Parameters<typeof resolvePortainerInstance>[0],
66
+ config: PortainerStackRedeployConfig,
67
+ signal?: AbortSignal,
68
+ ) {
69
+ const startedAt = new Date();
70
+ const instance = await resolvePortainerInstance(app, config.instanceId ?? null);
71
+ const timeoutMs = clampTimeoutMs(config.timeoutMs, instance.defaultTimeoutMs);
72
+ const mode = config.mode === 'webhook' ? 'webhook' : 'stack';
73
+
74
+ if (mode === 'webhook') {
75
+ await instance.client.triggerWebhook(config.webhookId ?? '', config.webhookTag, { timeoutMs, signal });
76
+ const finishedAt = new Date();
77
+ return {
78
+ ok: true,
79
+ instanceId: instance.id,
80
+ instanceName: instance.name,
81
+ endpointId: null,
82
+ stackId: null,
83
+ stackName: null,
84
+ stackType: 'webhook' as const,
85
+ stackStatus: 1,
86
+ gitReference: null,
87
+ webhookTag: config.webhookTag ? String(config.webhookTag).trim() : null,
88
+ appliedEnv: {},
89
+ appliedEnvCount: 0,
90
+ runningCount: 0,
91
+ totalCount: 0,
92
+ healthy: true,
93
+ containers: [] as PortainerContainerSummary[],
94
+ startedAt: startedAt.toISOString(),
95
+ finishedAt: finishedAt.toISOString(),
96
+ durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()),
97
+ };
98
+ }
99
+
100
+ const stackId = assertPositiveInt(config.stackId ?? undefined, 'Stack ID');
101
+ const rawStack = await instance.client.getRawStack(stackId, signal);
102
+ const stackDetail = toStackDetail(rawStack);
103
+
104
+ const hasExplicitEndpoint =
105
+ config.endpointId !== null && typeof config.endpointId !== 'undefined' && String(config.endpointId).trim() !== '';
106
+ const endpointId = hasExplicitEndpoint
107
+ ? assertPositiveInt(config.endpointId ?? undefined, 'Environment (Endpoint) ID')
108
+ : assertPositiveInt(rawStack.EndpointId, 'Stack Endpoint ID');
109
+
110
+ const { env, maskedEnv } = buildEffectiveStackEnv({
111
+ existingEnv: stackDetail.env,
112
+ strategy: config.envStrategy ?? 'merge',
113
+ dynamicEnv: config.dynamicEnv,
114
+ envText: config.envText,
115
+ envPairs: config.envPairs,
116
+ });
117
+
118
+ const prune = Boolean(config.prune);
119
+ const repullImage = Boolean(config.repullImage);
120
+ let updatedStack: RawPortainerStack;
121
+ let gitReferenceUsed: string | null = null;
122
+
123
+ if (stackDetail.isGitStack) {
124
+ gitReferenceUsed = normalizeGitReference(config.gitReference, stackDetail.gitReference);
125
+ const gitAuth = resolveGitAuthPayload(rawStack, instance);
126
+ updatedStack = await instance.client.redeployGitStack(
127
+ stackId,
128
+ endpointId,
129
+ {
130
+ env,
131
+ prune,
132
+ repullImage,
133
+ repositoryReferenceName: gitReferenceUsed,
134
+ ...gitAuth,
135
+ },
136
+ { timeoutMs, signal },
137
+ );
138
+ } else {
139
+ const stackFileContent = await instance.client.getStackFile(stackId, signal);
140
+ if (!stackFileContent.trim()) {
141
+ throw new PortainerApiError('Portainer stack file content is empty; cannot update non-Git stack', {
142
+ code: 'EMPTY_STACK_FILE',
143
+ });
144
+ }
145
+ updatedStack = await instance.client.updateComposeStack(
146
+ stackId,
147
+ endpointId,
148
+ {
149
+ stackFileContent,
150
+ env,
151
+ prune,
152
+ repullImage,
153
+ },
154
+ { timeoutMs, signal },
155
+ );
156
+ }
157
+
158
+ updatedStack = await instance.client.waitForStackSettlement(stackId, updatedStack, { timeoutMs, signal });
159
+
160
+ const stackName = String(updatedStack?.Name ?? rawStack.Name ?? '');
161
+ let containers: PortainerContainerSummary[] = [];
162
+ try {
163
+ containers = await instance.client.listStackContainers(endpointId, stackName, signal);
164
+ } catch {
165
+ containers = [];
166
+ }
167
+ const health = summarizeContainersHealth(containers);
168
+ const finishedAt = new Date();
169
+
170
+ return {
171
+ ok: true,
172
+ instanceId: instance.id,
173
+ instanceName: instance.name,
174
+ endpointId,
175
+ stackId,
176
+ stackName,
177
+ stackType: stackDetail.isGitStack ? ('git' as const) : ('compose' as const),
178
+ stackStatus: Number(updatedStack?.Status ?? rawStack.Status ?? 1),
179
+ gitReference: gitReferenceUsed,
180
+ appliedEnv: maskedEnv,
181
+ appliedEnvCount: env.length,
182
+ runningCount: health.runningCount,
183
+ totalCount: health.totalCount,
184
+ healthy: containers.length > 0 ? health.healthy : true,
185
+ containers,
186
+ startedAt: startedAt.toISOString(),
187
+ finishedAt: finishedAt.toISOString(),
188
+ durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()),
189
+ };
190
+ }
191
+
192
+ export class PortainerStackRedeployInstruction extends Instruction {
193
+ configSchema = Joi.object({
194
+ instanceId: numOrVar,
195
+ mode: Joi.string().valid('stack', 'webhook').default('stack'),
196
+ endpointId: numOrVar,
197
+ stackId: numOrVar,
198
+ webhookId: Joi.string().allow('', null),
199
+ webhookTag: Joi.string().allow('', null),
200
+ gitReference: Joi.string().allow('', null),
201
+ repullImage: Joi.boolean().default(false),
202
+ prune: Joi.boolean().default(false),
203
+ envStrategy: Joi.string().valid('merge', 'replace').default('merge'),
204
+ dynamicEnv: Joi.any(),
205
+ envText: Joi.string().allow('', null),
206
+ envPairs: Joi.array().items(
207
+ Joi.object({
208
+ name: Joi.string().allow('', null),
209
+ value: Joi.any(),
210
+ secret: Joi.boolean(),
211
+ }).unknown(true),
212
+ ),
213
+ timeoutMs: numOrVar,
214
+ ignoreFail: Joi.boolean().default(false),
215
+ }).unknown(true);
216
+
217
+ async run(node: FlowNodeModel, prevJob: JobModel, processor: Processor, options?: { signal?: AbortSignal }) {
218
+ const config = processor.getParsedValue(node.config ?? {}, node.id) as PortainerStackRedeployConfig;
219
+ return runPortainerWorkflowTask({
220
+ workflow: this.workflow,
221
+ node,
222
+ prevJob,
223
+ processor,
224
+ ignoreFail: config.ignoreFail,
225
+ signal: options?.signal,
226
+ execute: (signal) => executePortainerRedeploy(this.workflow.app, config, signal),
227
+ });
228
+ }
229
+
230
+ async resume(node: FlowNodeModel, job: JobModel) {
231
+ const config = (node.config ?? {}) as PortainerStackRedeployConfig;
232
+ if (config.ignoreFail) {
233
+ job.set('status', JOB_STATUS.RESOLVED);
234
+ }
235
+ return job;
236
+ }
237
+
238
+ async test(config: PortainerStackRedeployConfig) {
239
+ const startedAt = new Date();
240
+ try {
241
+ const result = await executePortainerRedeploy(this.workflow.app, config);
242
+ return {
243
+ status: JOB_STATUS.RESOLVED,
244
+ result,
245
+ };
246
+ } catch (error) {
247
+ return {
248
+ status: config.ignoreFail ? JOB_STATUS.RESOLVED : JOB_STATUS.FAILED,
249
+ result: formatFailureResult(error, startedAt),
250
+ };
251
+ }
252
+ }
253
+ }
254
+
255
+ export default PortainerStackRedeployInstruction;
@@ -0,0 +1,237 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ import type { Model } from '@nocobase/database';
11
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
12
+ import {
13
+ EXECUTION_STATUS,
14
+ JOB_STATUS,
15
+ type FlowNodeModel,
16
+ type IJob,
17
+ type JobModel,
18
+ type Processor,
19
+ } from '@nocobase/plugin-workflow';
20
+ import type Application from '@nocobase/server';
21
+ import { DEFAULT_TIMEOUT_MS, PORTAINER_INSTANCES_COLLECTION } from '../../shared/constants';
22
+ import type { ID } from '../../shared/types';
23
+ import { clampTimeoutMs, PortainerApiError, PortainerClient } from '../services/PortainerClient';
24
+
25
+ export interface ResolvedPortainerInstance {
26
+ id: number;
27
+ name: string;
28
+ baseUrl: string;
29
+ apiKey: string;
30
+ gitUsername?: string;
31
+ gitAccessToken?: string;
32
+ gitCredentialId?: number;
33
+ allowInsecureTls: boolean;
34
+ defaultTimeoutMs: number;
35
+ client: PortainerClient;
36
+ }
37
+
38
+ export async function decryptIfNeeded(app: Application, value: unknown): Promise<string> {
39
+ const raw = String(value ?? '').trim();
40
+ if (!raw) {
41
+ return '';
42
+ }
43
+ const decryptor = (app as unknown as { aesEncryptor?: { decrypt(v: string): Promise<string> | string } })
44
+ .aesEncryptor;
45
+ if (!decryptor) {
46
+ return raw;
47
+ }
48
+ try {
49
+ return await decryptor.decrypt(raw);
50
+ } catch {
51
+ return raw;
52
+ }
53
+ }
54
+
55
+ export async function resolvePortainerInstance(
56
+ app: Application,
57
+ instanceId?: ID | null,
58
+ ): Promise<ResolvedPortainerInstance> {
59
+ const repo = app.db.getRepository(PORTAINER_INSTANCES_COLLECTION);
60
+ if (!repo) {
61
+ throw new PortainerApiError('Portainer instances collection is not initialized', { code: 'NO_COLLECTION' });
62
+ }
63
+
64
+ let record: Model | null = null;
65
+ const trimmedId = instanceId !== null && typeof instanceId !== 'undefined' ? String(instanceId).trim() : '';
66
+
67
+ if (trimmedId) {
68
+ const numericId = Number(trimmedId);
69
+ if (!Number.isSafeInteger(numericId) || numericId <= 0) {
70
+ throw new PortainerApiError(`Invalid Portainer instance ID "${trimmedId}"`, { code: 'INVALID_INSTANCE' });
71
+ }
72
+ record = await repo.findOne({ filter: { id: numericId, enabled: true } });
73
+ if (!record) {
74
+ throw new PortainerApiError(`Portainer instance #${numericId} was not found or is disabled`, {
75
+ code: 'INSTANCE_NOT_FOUND',
76
+ });
77
+ }
78
+ } else {
79
+ record = await repo.findOne({ filter: { isDefault: true, enabled: true } });
80
+ if (!record) {
81
+ record = await repo.findOne({ filter: { enabled: true }, sort: ['id'] });
82
+ }
83
+ if (!record) {
84
+ throw new PortainerApiError('No enabled Portainer instance is configured', { code: 'NO_INSTANCE' });
85
+ }
86
+ }
87
+
88
+ const baseUrl = String(record.get('baseUrl') ?? '').trim();
89
+ const apiKey = await decryptIfNeeded(app, record.get('apiKey'));
90
+ const gitAccessToken = await decryptIfNeeded(app, record.get('gitAccessToken'));
91
+ const gitUsername = String(record.get('gitUsername') ?? '').trim() || undefined;
92
+ const rawCredId = Number(record.get('gitCredentialId') ?? 0);
93
+ const gitCredentialId = Number.isSafeInteger(rawCredId) && rawCredId > 0 ? rawCredId : undefined;
94
+ const allowInsecureTls = Boolean(record.get('allowInsecureTls'));
95
+ const defaultTimeoutMs = clampTimeoutMs(Number(record.get('defaultTimeoutMs') ?? DEFAULT_TIMEOUT_MS));
96
+
97
+ const client = new PortainerClient({
98
+ baseUrl,
99
+ apiKey,
100
+ allowInsecureTls,
101
+ timeoutMs: defaultTimeoutMs,
102
+ });
103
+
104
+ return {
105
+ id: Number(record.get('id')),
106
+ name: String(record.get('name') ?? ''),
107
+ baseUrl,
108
+ apiKey,
109
+ gitUsername,
110
+ gitAccessToken: gitAccessToken || undefined,
111
+ gitCredentialId,
112
+ allowInsecureTls,
113
+ defaultTimeoutMs,
114
+ client,
115
+ };
116
+ }
117
+
118
+ export function formatFailureResult(error: unknown, startedAt: Date) {
119
+ const finishedAt = new Date();
120
+ const durationMs = Math.max(0, finishedAt.getTime() - startedAt.getTime());
121
+ if (error instanceof PortainerApiError) {
122
+ return {
123
+ ok: false,
124
+ errorMessage: error.message,
125
+ errorCode: error.code ?? 'PORTAINER_ERROR',
126
+ httpStatus: error.status ?? null,
127
+ startedAt: startedAt.toISOString(),
128
+ finishedAt: finishedAt.toISOString(),
129
+ durationMs,
130
+ };
131
+ }
132
+ const message = error instanceof Error ? error.message : String(error);
133
+ return {
134
+ ok: false,
135
+ errorMessage: message,
136
+ errorCode: 'EXECUTION_ERROR',
137
+ httpStatus: null,
138
+ startedAt: startedAt.toISOString(),
139
+ finishedAt: finishedAt.toISOString(),
140
+ durationMs,
141
+ };
142
+ }
143
+
144
+ function resolveFailureJobStatus(ignoreFail: boolean | undefined, error: unknown): number {
145
+ if (ignoreFail) {
146
+ return JOB_STATUS.RESOLVED;
147
+ }
148
+ if (error instanceof PortainerApiError && error.code === 'ECONNABORTED') {
149
+ return JOB_STATUS.ABORTED;
150
+ }
151
+ return JOB_STATUS.FAILED;
152
+ }
153
+
154
+ /**
155
+ * Shared sync/async workflow execution bridge modeled after NocoBase's native RequestInstruction.
156
+ */
157
+ export async function runPortainerWorkflowTask<TResult extends Record<string, unknown>>(params: {
158
+ workflow: WorkflowPlugin;
159
+ node: FlowNodeModel;
160
+ prevJob: JobModel;
161
+ processor: Processor;
162
+ ignoreFail?: boolean;
163
+ signal?: AbortSignal;
164
+ execute: (signal?: AbortSignal) => Promise<TResult>;
165
+ }) {
166
+ const { workflow, node, prevJob, processor, ignoreFail, execute } = params;
167
+ const startedAt = new Date();
168
+ const sync = processor.isInstructionSync(node);
169
+
170
+ if (sync) {
171
+ try {
172
+ const result = await execute(params.signal);
173
+ return {
174
+ status: JOB_STATUS.RESOLVED,
175
+ result,
176
+ };
177
+ } catch (error) {
178
+ return {
179
+ status: resolveFailureJobStatus(ignoreFail, error),
180
+ result: formatFailureResult(error, startedAt),
181
+ };
182
+ }
183
+ }
184
+
185
+ const savedJob = processor.saveJob({
186
+ status: JOB_STATUS.PENDING,
187
+ nodeId: node.id,
188
+ nodeKey: node.key,
189
+ upstreamId: prevJob?.id ?? null,
190
+ });
191
+ const jobId = savedJob.id;
192
+
193
+ await processor.exit();
194
+ const abortHandle = processor.createBackgroundAbortHandle();
195
+ const jobDone: IJob = { status: JOB_STATUS.PENDING };
196
+
197
+ const settle = async () => {
198
+ try {
199
+ const result = await execute(abortHandle.signal);
200
+ jobDone.status = JOB_STATUS.RESOLVED;
201
+ jobDone.result = result;
202
+ } catch (error) {
203
+ processor.logger.error(
204
+ `[plugin-workflow-portainer] node (#${node.id}) execution failed: ${
205
+ error instanceof Error ? error.message : String(error)
206
+ }`,
207
+ );
208
+ jobDone.status = abortHandle.signal.aborted ? JOB_STATUS.ABORTED : resolveFailureJobStatus(ignoreFail, error);
209
+ jobDone.result = formatFailureResult(error, startedAt);
210
+ } finally {
211
+ abortHandle.dispose();
212
+ const job = (await workflow.app.db.getRepository('jobs').findOne({
213
+ filterByTk: jobId,
214
+ })) as JobModel | null;
215
+ if (job) {
216
+ const execution = await job.getExecution();
217
+ const aborted = await workflow.abortExecutionIfExpired(execution);
218
+ if (!aborted) {
219
+ await execution.reload();
220
+ await job.reload();
221
+ }
222
+ if (!aborted && execution.status === EXECUTION_STATUS.STARTED && job.status === JOB_STATUS.PENDING) {
223
+ job.set(jobDone);
224
+ await workflow.resume(job);
225
+ }
226
+ }
227
+ }
228
+ };
229
+
230
+ settle().catch((caught) => {
231
+ processor.logger.error(
232
+ `[plugin-workflow-portainer] async job settle failed (#${node.id}): ${
233
+ caught instanceof Error ? caught.message : String(caught)
234
+ }`,
235
+ );
236
+ });
237
+ }