@geek-fun/serverlessinsight 0.5.3 → 0.5.5

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 (34) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/commands/deploy.js +1 -0
  3. package/dist/src/common/aliyunClient/apigwOperations.js +153 -82
  4. package/dist/src/common/aliyunClient/ecsOperations.js +64 -13
  5. package/dist/src/common/aliyunClient/fc3Operations.js +15 -12
  6. package/dist/src/common/aliyunClient/index.js +3 -0
  7. package/dist/src/common/aliyunClient/ossOperations.js +4 -0
  8. package/dist/src/common/aliyunClient/ramOperations.js +45 -17
  9. package/dist/src/common/constants.js +14 -1
  10. package/dist/src/common/index.js +1 -0
  11. package/dist/src/common/lockManager.js +29 -1
  12. package/dist/src/common/sidUtils.js +24 -0
  13. package/dist/src/common/stateBackend/cosStateBackend.js +31 -0
  14. package/dist/src/common/stateBackend/ossStateBackend.js +32 -0
  15. package/dist/src/common/stateManager.js +2 -2
  16. package/dist/src/lang/en.js +13 -5
  17. package/dist/src/lang/zh-CN.js +38 -5
  18. package/dist/src/stack/aliyunStack/apigwPlanner.js +1 -1
  19. package/dist/src/stack/aliyunStack/apigwResource.js +18 -17
  20. package/dist/src/stack/aliyunStack/apigwTypes.js +4 -4
  21. package/dist/src/stack/aliyunStack/databaseResource.js +37 -21
  22. package/dist/src/stack/aliyunStack/fc3Executor.js +15 -5
  23. package/dist/src/stack/aliyunStack/fc3Planner.js +1 -1
  24. package/dist/src/stack/aliyunStack/fc3Resource.js +257 -132
  25. package/dist/src/stack/aliyunStack/ossResource.js +19 -8
  26. package/dist/src/stack/aliyunStack/tablestoreResource.js +19 -7
  27. package/dist/src/stack/scfStack/cosResource.js +21 -7
  28. package/dist/src/stack/scfStack/esServerlessResource.js +20 -7
  29. package/dist/src/stack/scfStack/scfResource.js +20 -7
  30. package/dist/src/stack/scfStack/tdsqlcResource.js +24 -7
  31. package/dist/src/types/domains/state.js +11 -2
  32. package/dist/src/validator/functionSchema.js +9 -2
  33. package/dist/tsconfig.tsbuildinfo +1 -1
  34. package/package.json +1 -1
@@ -11,6 +11,7 @@ const node_crypto_1 = __importDefault(require("node:crypto"));
11
11
  const node_child_process_1 = require("node:child_process");
12
12
  const constants_1 = require("./constants");
13
13
  const lang_1 = require("../lang");
14
+ const logger_1 = require("./logger");
14
15
  class LockError extends Error {
15
16
  constructor(message, lockInfo) {
16
17
  super(message);
@@ -85,6 +86,15 @@ const isLockStale = (lock) => {
85
86
  const now = Date.now();
86
87
  return now - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
87
88
  };
89
+ const isProcessAlive = (pid) => {
90
+ try {
91
+ process.kill(pid, 0);
92
+ return true;
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ };
88
98
  const getTimeAgo = (acquiredAt) => {
89
99
  const now = new Date();
90
100
  const minutesAgo = Math.floor((now.getTime() - acquiredAt.getTime()) / 60000);
@@ -150,7 +160,17 @@ const acquireLockInternal = async (statePath, operation, options = {}) => {
150
160
  }
151
161
  }
152
162
  else {
153
- // Lock exists, check if it's stale
163
+ if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
164
+ logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
165
+ processId: String(existingLock.processId),
166
+ hostname: existingLock.hostname,
167
+ user: existingLock.user,
168
+ acquiredAt: existingLock.acquiredAt,
169
+ }));
170
+ removeLockFile(lockPath);
171
+ attempt++;
172
+ continue;
173
+ }
154
174
  if (isLockStale(existingLock)) {
155
175
  // Lock is stale, but we don't auto-remove it
156
176
  // User must use force-unlock
@@ -160,6 +180,14 @@ const acquireLockInternal = async (statePath, operation, options = {}) => {
160
180
  if (Date.now() - startTime >= timeout) {
161
181
  throw new LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, exports.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
162
182
  }
183
+ const acquiredAt = new Date(existingLock.acquiredAt);
184
+ const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
185
+ const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
186
+ logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
187
+ user: existingLock.user,
188
+ timeAgo,
189
+ attempt: String(attempt + 1),
190
+ }));
163
191
  }
164
192
  // Wait before retrying with exponential backoff
165
193
  const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000); // Cap at 30 seconds
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * ServerlessInsight ID (SID) — logical resource identifier.
4
+ *
5
+ * Format: si:<provider>:<service>:<stage>:<id>
6
+ * Example: si:aliyun:rds:default:rm-abc123
7
+ *
8
+ * SID is a tool-generated identifier that uniquely locates a resource
9
+ * within a ServerlessInsight deployment. It is NOT a cloud-provider
10
+ * identifier — the provider-returned physical ID is stored separately
11
+ * in the `id` field of ResourceInstance.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.buildSid = void 0;
15
+ /**
16
+ * Build a ServerlessInsight ID (SID).
17
+ *
18
+ * @param provider - Cloud provider name (e.g. 'aliyun', 'tencent')
19
+ * @param service - Cloud service name (e.g. 'fc3', 'oss', 'rds', 'scf')
20
+ * @param stage - Deployment stage (e.g. 'default', 'dev', 'prod')
21
+ * @param id - Provider-returned physical resource identifier
22
+ */
23
+ const buildSid = (provider, service, stage, id) => `si:${provider}:${service}:${stage}:${id}`;
24
+ exports.buildSid = buildSid;
@@ -11,6 +11,8 @@ const node_child_process_1 = require("node:child_process");
11
11
  const types_1 = require("../../types");
12
12
  const constants_1 = require("../constants");
13
13
  const lockManager_1 = require("../lockManager");
14
+ const logger_1 = require("../logger");
15
+ const lang_1 = require("../../lang");
14
16
  const LOCK_KEY_SUFFIX = '.si-lock';
15
17
  const getUserEmail = () => {
16
18
  try {
@@ -33,6 +35,15 @@ const isLockStale = (lock) => {
33
35
  const acquiredAt = new Date(lock.acquiredAt).getTime();
34
36
  return Date.now() - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
35
37
  };
38
+ const isProcessAlive = (pid) => {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ };
36
47
  const promisifyGet = (cosClient, bucket, region, key) => {
37
48
  return new Promise((resolve, reject) => {
38
49
  cosClient.getObject({ Bucket: bucket, Region: region, Key: key }, (err, data) => {
@@ -75,6 +86,7 @@ const createCosStateBackend = (config) => {
75
86
  SecretId: config.accessKeyId,
76
87
  SecretKey: config.accessKeySecret,
77
88
  SecurityToken: config.securityToken,
89
+ Timeout: constants_1.OSS_STATE_REQUEST_TIMEOUT_MS,
78
90
  });
79
91
  const lockKey = `${config.key}${LOCK_KEY_SUFFIX}`;
80
92
  const readObject = async (key) => {
@@ -117,12 +129,31 @@ const createCosStateBackend = (config) => {
117
129
  }
118
130
  }
119
131
  else {
132
+ if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
133
+ logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
134
+ processId: String(existingLock.processId),
135
+ hostname: existingLock.hostname,
136
+ user: existingLock.user,
137
+ acquiredAt: existingLock.acquiredAt,
138
+ }));
139
+ await deleteObject(lockKey);
140
+ attempt++;
141
+ continue;
142
+ }
120
143
  if (isLockStale(existingLock)) {
121
144
  throw new lockManager_1.LockError(`State is currently locked (stale lock detected).\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
122
145
  }
123
146
  if (Date.now() - startTime >= timeout) {
124
147
  throw new lockManager_1.LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
125
148
  }
149
+ const acquiredAt = new Date(existingLock.acquiredAt);
150
+ const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
151
+ const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
152
+ logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
153
+ user: existingLock.user,
154
+ timeAgo,
155
+ attempt: String(attempt + 1),
156
+ }));
126
157
  }
127
158
  const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000);
128
159
  await sleep(delay);
@@ -11,6 +11,8 @@ const node_child_process_1 = require("node:child_process");
11
11
  const types_1 = require("../../types");
12
12
  const constants_1 = require("../constants");
13
13
  const lockManager_1 = require("../lockManager");
14
+ const logger_1 = require("../logger");
15
+ const lang_1 = require("../../lang");
14
16
  const LOCK_KEY_SUFFIX = '.si-lock';
15
17
  const getUserEmail = () => {
16
18
  try {
@@ -33,6 +35,15 @@ const isLockStale = (lock) => {
33
35
  const acquiredAt = new Date(lock.acquiredAt).getTime();
34
36
  return Date.now() - acquiredAt > constants_1.STALE_LOCK_THRESHOLD;
35
37
  };
38
+ const isProcessAlive = (pid) => {
39
+ try {
40
+ process.kill(pid, 0);
41
+ return true;
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ };
36
47
  const createOssStateBackend = (config) => {
37
48
  const ossClient = new ali_oss_1.default({
38
49
  accessKeyId: config.accessKeyId,
@@ -40,6 +51,8 @@ const createOssStateBackend = (config) => {
40
51
  region: `oss-${config.region}`,
41
52
  bucket: config.bucket,
42
53
  stsToken: config.securityToken,
54
+ timeout: constants_1.OSS_STATE_REQUEST_TIMEOUT_MS,
55
+ connectTimeout: constants_1.OSS_STATE_CONNECT_TIMEOUT_MS,
43
56
  });
44
57
  const lockKey = `${config.key}${LOCK_KEY_SUFFIX}`;
45
58
  const readObject = async (key) => {
@@ -98,12 +111,31 @@ const createOssStateBackend = (config) => {
98
111
  }
99
112
  }
100
113
  else {
114
+ if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
115
+ logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
116
+ processId: String(existingLock.processId),
117
+ hostname: existingLock.hostname,
118
+ user: existingLock.user,
119
+ acquiredAt: existingLock.acquiredAt,
120
+ }));
121
+ await deleteObject(lockKey);
122
+ attempt++;
123
+ continue;
124
+ }
101
125
  if (isLockStale(existingLock)) {
102
126
  throw new lockManager_1.LockError(`State is currently locked (stale lock detected).\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
103
127
  }
104
128
  if (Date.now() - startTime >= timeout) {
105
129
  throw new lockManager_1.LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, lockManager_1.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
106
130
  }
131
+ const acquiredAt = new Date(existingLock.acquiredAt);
132
+ const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
133
+ const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
134
+ logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
135
+ user: existingLock.user,
136
+ timeAgo,
137
+ attempt: String(attempt + 1),
138
+ }));
107
139
  }
108
140
  const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000);
109
141
  await sleep(delay);
@@ -124,8 +124,8 @@ const getRoleArnFromState = (state) => {
124
124
  for (const [logicalId, resourceState] of Object.entries(allResources)) {
125
125
  if (logicalId.startsWith('functions.')) {
126
126
  const ramRoleInstance = resourceState.instances?.find((i) => i.type === 'ALIYUN_RAM_ROLE');
127
- if (ramRoleInstance?.arn) {
128
- return ramRoleInstance.arn;
127
+ if (ramRoleInstance?.roleArn) {
128
+ return ramRoleInstance.roleArn;
129
129
  }
130
130
  }
131
131
  }
@@ -180,6 +180,8 @@ exports.en = {
180
180
  ACQUIRING_LOCK: 'Acquiring state lock...',
181
181
  LOCK_ACQUIRED: 'Lock acquired',
182
182
  LOCK_RELEASED: '✓ Lock released',
183
+ LOCK_WAITING: 'State is locked by {{user}} ({{timeAgo}}). Waiting to acquire lock... (attempt {{attempt}})',
184
+ LOCK_AUTO_RELEASED_DEAD_PROCESS: 'Auto-releasing stale lock held by dead process (PID {{processId}} on {{hostname}}). Lock was held by {{user}} since {{acquiredAt}}.',
183
185
  FAILED_TO_RELEASE_LOCK: 'Failed to release lock',
184
186
  NO_LOCK_FOUND: 'No lock found',
185
187
  LOCK_ID_MISMATCH: 'Lock ID mismatch. Current lock ID is {{actualId}}, but you provided {{providedId}}',
@@ -224,12 +226,18 @@ exports.en = {
224
226
  APIGW_BINDING_DOMAIN: 'Binding custom domain: {{domain}}',
225
227
  APIGW_DOMAIN_BOUND_SUCCESS: 'Successfully bound domain: {{domain}}',
226
228
  APIGW_DOMAIN_OWNERSHIP_FAILED: 'Domain ownership verification failed for: {{domain}}',
227
- APIGW_ATTEMPTING_AUTO_VERIFICATION: 'Attempting automatic DNS verification with token: {{token}}',
228
- APIGW_RETRYING_DOMAIN_BINDING: 'Retrying domain binding after DNS verification...',
229
+ APIGW_ENSURING_CNAME: 'Ensuring CNAME record exists for domain: {{domain}}',
230
+ APIGW_PUBLIC_DNS_CHECKING: 'Checking public DNS resolution for: {{domain}}',
231
+ APIGW_PUBLIC_DNS_CHECK_ATTEMPT: 'Public DNS resolution check (attempt {{attempt}}/{{max}})...',
232
+ APIGW_PUBLIC_DNS_RESOLVED: 'Public DNS resolution confirmed for: {{domain}}',
233
+ APIGW_PUBLIC_DNS_TIMEOUT: 'Public DNS resolution could not be verified for {{domain}}. Proceeding anyway...',
234
+ APIGW_TXT_FALLBACK: 'CNAME verification insufficient for {{domain}}, adding TXT verification record as fallback...',
235
+ APIGW_TXT_ADDING_RECORD: 'Adding TXT verification record: RR={{rr}}, Value={{value}}',
236
+ APIGW_TXT_RECORD_ALREADY_EXISTS: 'TXT verification record already exists: {{rr}}',
237
+ APIGW_TXT_ADD_FAILED: 'Failed to add TXT verification record: {{error}}',
238
+ APIGW_DOMAIN_BIND_RETRY: 'Retrying domain binding (attempt {{attempt}}/{{max}}, waiting for DNS propagation)...',
239
+ APIGW_DOMAIN_BIND_RETRY_FAILED: 'Domain binding retry {{attempt}} failed: {{error}}',
229
240
  APIGW_DOMAIN_BOUND_AFTER_VERIFICATION: 'Successfully bound domain after verification: {{domain}}',
230
- APIGW_AUTO_VERIFICATION_FAILED: 'Automatic verification failed: {{error}}',
231
- APIGW_NO_VERIFICATION_TOKEN: 'Could not extract verification token from error response',
232
- APIGW_MANUAL_VERIFICATION_REQUIRED: 'Please manually verify domain ownership in Aliyun console',
233
241
  APIGW_VERIFICATION_HEADER: 'Domain Ownership Verification Required',
234
242
  APIGW_VERIFICATION_DOMAIN: 'Domain: {{domain}}',
235
243
  APIGW_VERIFICATION_INSTRUCTIONS: 'To verify domain ownership, add ONE of the following DNS records:',
@@ -176,6 +176,33 @@ exports.zhCN = {
176
176
  PARTIAL_FAILURE_NEXT_STEPS: '后续步骤: 1) 查看上面的错误, 2) 修复配置问题, 3) 再次运行 deploy 继续。',
177
177
  FAILED_TO_EXECUTE_ACTION: '执行 {{action}} 失败: {{logicalId}}: {{error}}',
178
178
  STATE_PERSISTED_AFTER_OPERATION: '{{action}} {{resourceId}} 后状态已持久化',
179
+ // Lock messages
180
+ ACQUIRING_LOCK: '正在获取状态锁...',
181
+ LOCK_ACQUIRED: '锁已获取',
182
+ LOCK_RELEASED: '✓ 锁已释放',
183
+ LOCK_WAITING: '状态被 {{user}} 锁定({{timeAgo}})。等待获取锁...(第 {{attempt}} 次尝试)',
184
+ LOCK_AUTO_RELEASED_DEAD_PROCESS: '自动释放已终止进程持有的过期锁(PID {{processId}},主机 {{hostname}})。锁由 {{user}} 于 {{acquiredAt}} 获取。',
185
+ FAILED_TO_RELEASE_LOCK: '释放锁失败',
186
+ NO_LOCK_FOUND: '未找到锁',
187
+ LOCK_ID_MISMATCH: '锁 ID 不匹配。当前锁 ID 为 {{actualId}},但您提供了 {{providedId}}',
188
+ CURRENT_LOCK_INFO: '当前锁信息:',
189
+ FORCE_UNLOCK_WARNING: '\n⚠️ 警告: 强制解锁可能会导致状态损坏,如果另一个操作仍在运行!',
190
+ FORCE_UNLOCK_CONFIRM: '您确定吗?(yes/no): ',
191
+ FORCE_UNLOCK_CANCELLED: '强制解锁已取消',
192
+ PLAN_COMMAND_NOT_SUPPORTED: '此提供商不支持 Plan 命令',
193
+ // Lock info formatting
194
+ LOCK_INFO_HEADER: '锁信息:',
195
+ LOCK_INFO_ID: ' ID: {{id}}',
196
+ LOCK_INFO_HELD_BY: ' 持有者: {{user}}',
197
+ LOCK_INFO_PROCESS: ' 进程: si {{operation}} (PID {{processId}})',
198
+ LOCK_INFO_HOST: ' 主机: {{hostname}}',
199
+ LOCK_INFO_ACQUIRED: ' 获取时间: {{acquiredAt}} ({{timeAgo}})',
200
+ LOCK_INFO_OPERATION: ' 操作: {{operation}}',
201
+ LOCK_TIME_AGO_LESS_THAN_MINUTE: '不到一分钟前',
202
+ LOCK_TIME_AGO_ONE_MINUTE: '1 分钟前',
203
+ LOCK_TIME_AGO_MINUTES: '{{minutes}} 分钟前',
204
+ LOCK_TIME_AGO_ONE_HOUR: '1 小时前',
205
+ LOCK_TIME_AGO_HOURS: '{{hours}} 小时前',
179
206
  // API Gateway messages
180
207
  APIGW_GROUP_FOUND_REUSING: '找到现有 API 分组: {{groupName}},将复用它',
181
208
  APIGW_DOMAIN_BINDING_FAILED: '绑定自定义域名失败: {{error}}',
@@ -199,12 +226,18 @@ exports.zhCN = {
199
226
  APIGW_BINDING_DOMAIN: '绑定自定义域名: {{domain}}',
200
227
  APIGW_DOMAIN_BOUND_SUCCESS: '成功绑定域名: {{domain}}',
201
228
  APIGW_DOMAIN_OWNERSHIP_FAILED: '域名所有权验证失败: {{domain}}',
202
- APIGW_ATTEMPTING_AUTO_VERIFICATION: '尝试使用令牌自动进行 DNS 验证: {{token}}',
203
- APIGW_RETRYING_DOMAIN_BINDING: 'DNS 验证后重试域名绑定...',
229
+ APIGW_ENSURING_CNAME: '确保域名 CNAME 记录存在: {{domain}}',
230
+ APIGW_PUBLIC_DNS_CHECKING: '检查公共 DNS 解析: {{domain}}',
231
+ APIGW_PUBLIC_DNS_CHECK_ATTEMPT: '公共 DNS 解析检查(第 {{attempt}}/{{max}} 次尝试)...',
232
+ APIGW_PUBLIC_DNS_RESOLVED: '已确认公共 DNS 解析: {{domain}}',
233
+ APIGW_PUBLIC_DNS_TIMEOUT: '无法验证 {{domain}} 的公共 DNS 解析。继续执行...',
234
+ APIGW_TXT_FALLBACK: 'CNAME 验证不足以绑定 {{domain}},添加 TXT 验证记录作为备选...',
235
+ APIGW_TXT_ADDING_RECORD: '添加 TXT 验证记录: RR={{rr}}, 值={{value}}',
236
+ APIGW_TXT_RECORD_ALREADY_EXISTS: 'TXT 验证记录已存在: {{rr}}',
237
+ APIGW_TXT_ADD_FAILED: '添加 TXT 验证记录失败: {{error}}',
238
+ APIGW_DOMAIN_BIND_RETRY: '重试域名绑定(第 {{attempt}}/{{max}} 次尝试,等待 DNS 传播)...',
239
+ APIGW_DOMAIN_BIND_RETRY_FAILED: '域名绑定第 {{attempt}} 次重试失败: {{error}}',
204
240
  APIGW_DOMAIN_BOUND_AFTER_VERIFICATION: '验证后成功绑定域名: {{domain}}',
205
- APIGW_AUTO_VERIFICATION_FAILED: '自动验证失败: {{error}}',
206
- APIGW_NO_VERIFICATION_TOKEN: '无法从错误响应中提取验证令牌',
207
- APIGW_MANUAL_VERIFICATION_REQUIRED: '请在阿里云控制台手动验证域名所有权',
208
241
  APIGW_VERIFICATION_HEADER: '需要域名所有权验证',
209
242
  APIGW_VERIFICATION_DOMAIN: '域名: {{domain}}',
210
243
  APIGW_VERIFICATION_INSTRUCTIONS: '要验证域名所有权,请添加以下 DNS 记录之一:',
@@ -27,7 +27,7 @@ const generateApigwPlan = async (context, state, events, serviceName) => {
27
27
  const eventItems = await Promise.all(events.map(async (event) => {
28
28
  const logicalId = `events.${event.key}`;
29
29
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
30
- const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName);
30
+ const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
31
31
  const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
32
32
  const client = (0, aliyunClient_1.createAliyunClient)(context);
33
33
  // Build desired definition including triggers
@@ -4,12 +4,13 @@ exports.deleteApigwResource = exports.updateApigwResource = exports.readApigwRes
4
4
  const aliyunClient_1 = require("../../common/aliyunClient");
5
5
  const apigwTypes_1 = require("./apigwTypes");
6
6
  const stateManager_1 = require("../../common/stateManager");
7
+ const common_1 = require("../../common");
7
8
  const logger_1 = require("../../common/logger");
8
9
  const lang_1 = require("../../lang");
9
- const buildApigwGroupInstanceFromProvider = (info, region) => {
10
+ const buildApigwGroupInstanceFromProvider = (info, stage) => {
10
11
  return {
11
12
  type: 'ALIYUN_APIGW_GROUP',
12
- arn: `arn:acs:apigateway:${region}:group/${info.groupId}`,
13
+ sid: (0, common_1.buildSid)('aliyun', 'apigateway', stage, info.groupId ?? ''),
13
14
  id: info.groupId ?? '',
14
15
  groupId: info.groupId ?? null,
15
16
  groupName: info.groupName ?? null,
@@ -26,10 +27,10 @@ const buildApigwGroupInstanceFromProvider = (info, region) => {
26
27
  trafficLimit: info.trafficLimit ?? null,
27
28
  };
28
29
  };
29
- const buildApigwApiInstanceFromProvider = (info, region, groupId) => {
30
+ const buildApigwApiInstanceFromProvider = (info, stage, groupId) => {
30
31
  return {
31
32
  type: 'ALIYUN_APIGW_API',
32
- arn: `arn:acs:apigateway:${region}:group/${groupId}/api/${info.apiId}`,
33
+ sid: (0, common_1.buildSid)('aliyun', 'apigateway', stage, `${groupId}/${info.apiId}`),
33
34
  id: info.apiId ?? '',
34
35
  apiId: info.apiId ?? null,
35
36
  apiName: info.apiName ?? null,
@@ -45,10 +46,10 @@ const buildApigwApiInstanceFromProvider = (info, region, groupId) => {
45
46
  modifiedTime: info.modifiedTime ?? null,
46
47
  };
47
48
  };
48
- const buildApigwDeploymentInstance = (groupId, apiId, stageName, region) => {
49
+ const buildApigwDeploymentInstance = (groupId, apiId, stageName, stage) => {
49
50
  return {
50
51
  type: 'ALIYUN_APIGW_DEPLOYMENT',
51
- arn: `arn:acs:apigateway:${region}:group/${groupId}/api/${apiId}/deployment/${stageName}`,
52
+ sid: (0, common_1.buildSid)('aliyun', 'apigateway', stage, `${groupId}/${apiId}/${stageName}`),
52
53
  id: `${groupId}/${apiId}/${stageName}`,
53
54
  groupId,
54
55
  apiId,
@@ -58,7 +59,7 @@ const buildApigwDeploymentInstance = (groupId, apiId, stageName, region) => {
58
59
  const createApigwResource = async (context, event, serviceName, roleArn, state) => {
59
60
  const logicalId = `events.${event.key}`;
60
61
  const client = (0, aliyunClient_1.createAliyunClient)(context);
61
- const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName);
62
+ const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
62
63
  let groupId;
63
64
  try {
64
65
  const existingGroup = await client.apigw.findApiGroupByName(groupConfig.groupName);
@@ -80,7 +81,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
80
81
  throw new Error(`Failed to get API group info after creation: ${groupId}`);
81
82
  }
82
83
  const instances = [
83
- buildApigwGroupInstanceFromProvider(groupInfo, context.region),
84
+ buildApigwGroupInstanceFromProvider(groupInfo, context.stage),
84
85
  ];
85
86
  const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
86
87
  const partialResourceState = {
@@ -106,12 +107,12 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
106
107
  state = (0, stateManager_1.setResource)(state, logicalId, partialResourceState);
107
108
  // Create APIs and deployments for each trigger
108
109
  for (const trigger of event.triggers) {
109
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, roleArn);
110
+ const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
110
111
  const apiId = await client.apigw.createApi(apiConfig);
111
112
  // Get API info for state
112
113
  const apiInfo = await client.apigw.getApi(groupId, apiId);
113
114
  if (apiInfo) {
114
- instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.region, groupId));
115
+ instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.stage, groupId));
115
116
  }
116
117
  // Deploy API to RELEASE stage
117
118
  const deploymentConfig = {
@@ -121,7 +122,7 @@ const createApigwResource = async (context, event, serviceName, roleArn, state)
121
122
  description: `${serviceName} API deployment for ${trigger.method} ${trigger.path}`,
122
123
  };
123
124
  await client.apigw.deployApi(deploymentConfig);
124
- instances.push(buildApigwDeploymentInstance(groupId, apiId, 'RELEASE', context.region));
125
+ instances.push(buildApigwDeploymentInstance(groupId, apiId, 'RELEASE', context.stage));
125
126
  const updatedResourceState = {
126
127
  mode: 'managed',
127
128
  region: context.region,
@@ -208,19 +209,19 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
208
209
  return (0, exports.createApigwResource)(context, event, serviceName, roleArn, state);
209
210
  }
210
211
  const groupId = groupInstance.id;
211
- const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName);
212
+ const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
212
213
  await client.apigw.updateApiGroup(groupId, groupConfig);
213
214
  const groupInfo = await client.apigw.getApiGroup(groupId);
214
215
  if (!groupInfo) {
215
216
  throw new Error(`Failed to get API group info after update: ${groupId}`);
216
217
  }
217
218
  const instances = [
218
- buildApigwGroupInstanceFromProvider(groupInfo, context.region),
219
+ buildApigwGroupInstanceFromProvider(groupInfo, context.stage),
219
220
  ];
220
221
  const existingApis = existingInstances.filter((i) => i.type === 'ALIYUN_APIGW_API');
221
222
  const neededApiKeys = new Set();
222
223
  for (const trigger of event.triggers) {
223
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, roleArn);
224
+ const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, groupId, serviceName, context.region, context.stage, roleArn);
224
225
  const apiKey = (0, apigwTypes_1.generateApiKey)(trigger.method, trigger.path);
225
226
  neededApiKeys.add(apiKey);
226
227
  const existingApi = existingApis.find((a) => {
@@ -236,7 +237,7 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
236
237
  }
237
238
  const apiInfo = await client.apigw.getApi(groupId, apiId);
238
239
  if (apiInfo) {
239
- instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.region, groupId));
240
+ instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.stage, groupId));
240
241
  }
241
242
  const deploymentConfig = {
242
243
  groupId,
@@ -245,13 +246,13 @@ const updateApigwResource = async (context, event, serviceName, roleArn, state)
245
246
  description: `${serviceName} API deployment for ${trigger.method} ${trigger.path}`,
246
247
  };
247
248
  await client.apigw.deployApi(deploymentConfig);
248
- instances.push(buildApigwDeploymentInstance(groupId, apiId, 'RELEASE', context.region));
249
+ instances.push(buildApigwDeploymentInstance(groupId, apiId, 'RELEASE', context.stage));
249
250
  }
250
251
  for (const existingApi of existingApis) {
251
252
  const apiInfo = await client.apigw.getApi(groupId, existingApi.id);
252
253
  if (apiInfo) {
253
254
  const isNeeded = event.triggers.some((t) => {
254
- const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, roleArn).apiName;
255
+ const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, groupId, serviceName, context.region, context.stage, roleArn).apiName;
255
256
  return apiInfo.apiName === expectedName;
256
257
  });
257
258
  if (!isNeeded) {
@@ -5,9 +5,9 @@ const common_1 = require("../../common");
5
5
  /**
6
6
  * Convert EventDomain to API Gateway group config
7
7
  */
8
- const eventToApigwGroupConfig = (event, serviceName) => {
8
+ const eventToApigwGroupConfig = (event, serviceName, stage) => {
9
9
  return {
10
- groupName: `${serviceName}-agw-group`.replace(/_/g, '-'),
10
+ groupName: `${serviceName}-${stage}-agw-group`.replace(/_/g, '-'),
11
11
  description: `API Gateway group for ${serviceName}`,
12
12
  };
13
13
  };
@@ -51,7 +51,7 @@ const resolveFunctionReference = (backendRef) => {
51
51
  /**
52
52
  * Convert EventDomain trigger to API Gateway API config
53
53
  */
54
- const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, roleArn) => {
54
+ const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, stage, roleArn) => {
55
55
  const method = trigger.method;
56
56
  const path = trigger.path;
57
57
  const backend = trigger.backend;
@@ -59,7 +59,7 @@ const triggerToApigwApiConfig = (event, trigger, groupId, serviceName, region, r
59
59
  const apiKey = (0, exports.generateApiKey)(method, path);
60
60
  return {
61
61
  groupId,
62
- apiName: `${event.name}-agw-api-${apiKey}`.replace(/_/g, '-'),
62
+ apiName: `${event.name}-${stage}-agw-api-${apiKey}`.replace(/_/g, '-'),
63
63
  visibility: 'PRIVATE',
64
64
  authType: 'ANONYMOUS',
65
65
  requestConfig: {
@@ -5,9 +5,11 @@ const aliyunClient_1 = require("../../common/aliyunClient");
5
5
  const rdsTypes_1 = require("./rdsTypes");
6
6
  const esServerlessTypes_1 = require("./esServerlessTypes");
7
7
  const stateManager_1 = require("../../common/stateManager");
8
- const buildRdsInstanceFromProvider = (info, arn) => {
8
+ const common_1 = require("../../common");
9
+ const logger_1 = require("../../common/logger");
10
+ const buildRdsInstanceFromProvider = (info, sid) => {
9
11
  return {
10
- arn,
12
+ sid,
11
13
  id: info.dbInstanceId ?? '',
12
14
  dbInstanceId: info.dbInstanceId ?? null,
13
15
  dbInstanceDescription: info.dbInstanceDescription ?? null,
@@ -38,9 +40,9 @@ const buildRdsInstanceFromProvider = (info, arn) => {
38
40
  multiAZ: info.multiAZ ?? null,
39
41
  };
40
42
  };
41
- const buildEsInstanceFromProvider = (info, arn) => {
43
+ const buildEsInstanceFromProvider = (info, sid) => {
42
44
  return {
43
- arn,
45
+ sid,
44
46
  id: info.appId ?? '',
45
47
  appId: info.appId ?? null,
46
48
  appName: info.appName ?? null,
@@ -98,7 +100,6 @@ const createDatabaseResource = async (context, database, state) => {
98
100
  let instanceId;
99
101
  let definition;
100
102
  let instance;
101
- let arn;
102
103
  let resourceType;
103
104
  if (database.type === "ELASTICSEARCH_SERVERLESS" /* DatabaseEnum.ELASTICSEARCH_SERVERLESS */) {
104
105
  // Create Elasticsearch Serverless app
@@ -110,8 +111,8 @@ const createDatabaseResource = async (context, database, state) => {
110
111
  throw new Error(`Failed to refresh state for ES app: ${instanceId}`);
111
112
  }
112
113
  definition = (0, esServerlessTypes_1.extractEsDefinition)(config);
113
- arn = `arn:acs:elasticsearch:${context.region}:${context.accountId}:serverless:${instanceId}`;
114
- instance = buildEsInstanceFromProvider(appInfo, arn);
114
+ const sid = (0, common_1.buildSid)('aliyun', 'es', context.stage, instanceId);
115
+ instance = buildEsInstanceFromProvider(appInfo, sid);
115
116
  resourceType = 'ALIYUN_ES_SERVERLESS';
116
117
  }
117
118
  else if ([
@@ -128,8 +129,8 @@ const createDatabaseResource = async (context, database, state) => {
128
129
  throw new Error(`Failed to refresh state for RDS instance: ${instanceId}`);
129
130
  }
130
131
  definition = (0, rdsTypes_1.extractRdsDefinition)(config);
131
- arn = `arn:acs:rds:${context.region}:${context.accountId}:dbinstance:${instanceId}`;
132
- instance = buildRdsInstanceFromProvider(rdsInfo, arn);
132
+ const sid = (0, common_1.buildSid)('aliyun', 'rds', context.stage, instanceId);
133
+ instance = buildRdsInstanceFromProvider(rdsInfo, sid);
133
134
  resourceType = 'ALIYUN_RDS_SERVERLESS';
134
135
  }
135
136
  else {
@@ -167,7 +168,6 @@ const updateDatabaseResource = async (context, database, instanceId, resourceTyp
167
168
  const client = (0, aliyunClient_1.createAliyunClient)(context);
168
169
  let definition;
169
170
  let instance;
170
- let arn;
171
171
  if (resourceType === 'ALIYUN_ES_SERVERLESS') {
172
172
  const config = (0, esServerlessTypes_1.databaseToEsConfig)(database);
173
173
  await client.es.updateApp(instanceId, config);
@@ -177,8 +177,8 @@ const updateDatabaseResource = async (context, database, instanceId, resourceTyp
177
177
  throw new Error(`Failed to refresh state for ES app: ${instanceId}`);
178
178
  }
179
179
  definition = (0, esServerlessTypes_1.extractEsDefinition)(config);
180
- arn = `arn:acs:elasticsearch:${context.region}:${context.accountId}:serverless:${instanceId}`;
181
- instance = buildEsInstanceFromProvider(appInfo, arn);
180
+ const sid = (0, common_1.buildSid)('aliyun', 'es', context.stage, instanceId);
181
+ instance = buildEsInstanceFromProvider(appInfo, sid);
182
182
  }
183
183
  else if (resourceType === 'ALIYUN_RDS_SERVERLESS') {
184
184
  const config = (0, rdsTypes_1.databaseToRdsConfig)(database);
@@ -189,8 +189,8 @@ const updateDatabaseResource = async (context, database, instanceId, resourceTyp
189
189
  throw new Error(`Failed to refresh state for RDS instance: ${instanceId}`);
190
190
  }
191
191
  definition = (0, rdsTypes_1.extractRdsDefinition)(config);
192
- arn = `arn:acs:rds:${context.region}:${context.accountId}:dbinstance:${instanceId}`;
193
- instance = buildRdsInstanceFromProvider(rdsInfo, arn);
192
+ const sid = (0, common_1.buildSid)('aliyun', 'rds', context.stage, instanceId);
193
+ instance = buildRdsInstanceFromProvider(rdsInfo, sid);
194
194
  }
195
195
  else {
196
196
  throw new Error(`Unsupported resource type: ${resourceType}`);
@@ -214,14 +214,30 @@ const updateDatabaseResource = async (context, database, instanceId, resourceTyp
214
214
  exports.updateDatabaseResource = updateDatabaseResource;
215
215
  const deleteDatabaseResource = async (context, instanceId, resourceType, logicalId, state) => {
216
216
  const client = (0, aliyunClient_1.createAliyunClient)(context);
217
- if (resourceType === 'ALIYUN_ES_SERVERLESS') {
218
- await client.es.deleteApp(instanceId);
219
- }
220
- else if (resourceType === 'ALIYUN_RDS_SERVERLESS') {
221
- await client.rds.deleteInstance(instanceId);
217
+ try {
218
+ if (resourceType === 'ALIYUN_ES_SERVERLESS') {
219
+ await client.es.deleteApp(instanceId);
220
+ }
221
+ else if (resourceType === 'ALIYUN_RDS_SERVERLESS') {
222
+ await client.rds.deleteInstance(instanceId);
223
+ }
224
+ else {
225
+ throw new Error(`Unsupported resource type: ${resourceType}`);
226
+ }
222
227
  }
223
- else {
224
- throw new Error(`Unsupported resource type: ${resourceType}`);
228
+ catch (err) {
229
+ const errorCode = err?.code;
230
+ const errorMessage = err?.message ?? '';
231
+ if (errorCode === 'InvalidDBInstanceId.NotFound' ||
232
+ errorCode === 'AppNotFound' ||
233
+ errorCode === 'NotFound' ||
234
+ errorMessage.includes('not found') ||
235
+ errorMessage.includes('NotFound')) {
236
+ logger_1.logger.warn(`Database resource ${instanceId} not found in provider, skipping deletion`);
237
+ }
238
+ else {
239
+ throw err;
240
+ }
225
241
  }
226
242
  return (0, stateManager_1.removeResource)(state, logicalId);
227
243
  };