@geek-fun/serverlessinsight 0.8.2 → 0.8.3

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 (119) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +14 -0
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +14 -0
  3. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +348 -0
  4. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +14 -0
  5. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +114 -0
  6. package/.serverlessinsight/state-insight-volc-destroy-app-insight-volc-destroy.json.backup +1 -0
  7. package/README.md +26 -18
  8. package/README.zh-CN.md +19 -6
  9. package/dist/package.json +3 -1
  10. package/dist/src/commands/deploy.js +87 -4
  11. package/dist/src/commands/destroy.js +61 -10
  12. package/dist/src/commands/forceUnlock.js +8 -0
  13. package/dist/src/commands/index.js +34 -2
  14. package/dist/src/commands/login.js +195 -0
  15. package/dist/src/commands/logout.js +17 -0
  16. package/dist/src/commands/show.js +15 -7
  17. package/dist/src/commands/whoami.js +20 -0
  18. package/dist/src/common/aliyunClient/apigwOperations.js +327 -30
  19. package/dist/src/common/aliyunClient/esOperations.js +43 -29
  20. package/dist/src/common/aliyunClient/fc3Operations.js +481 -207
  21. package/dist/src/common/aliyunClient/ossOperations.js +165 -13
  22. package/dist/src/common/aliyunClient/rdsOperations.js +143 -39
  23. package/dist/src/common/aliyunClient/slsOperations.js +56 -26
  24. package/dist/src/common/aliyunClient/tablestoreOperations.js +25 -22
  25. package/dist/src/common/apiClient.js +102 -0
  26. package/dist/src/common/constants.js +9 -4
  27. package/dist/src/common/credentialStore.js +94 -0
  28. package/dist/src/common/credentials.js +2 -0
  29. package/dist/src/common/eventQueue.js +208 -0
  30. package/dist/src/common/hashUtils.js +87 -11
  31. package/dist/src/common/imsClient.js +1 -0
  32. package/dist/src/common/index.js +3 -0
  33. package/dist/src/common/lockManager.js +61 -54
  34. package/dist/src/common/logger.js +2 -0
  35. package/dist/src/common/polling.js +54 -0
  36. package/dist/src/common/reportResourceEvent.js +8 -0
  37. package/dist/src/common/runtimeMapper.js +11 -12
  38. package/dist/src/common/stateBackend/index.js +10 -1
  39. package/dist/src/common/stateBackend/localStateBackend.js +4 -1
  40. package/dist/src/common/stateBackend/remoteStateBackend.js +6 -3
  41. package/dist/src/common/stateBackend/saasStateBackend.js +266 -0
  42. package/dist/src/common/stateManager.js +135 -13
  43. package/dist/src/common/tencentClient/cosOperations.js +180 -3
  44. package/dist/src/common/tencentClient/esOperations.js +110 -46
  45. package/dist/src/common/tencentClient/index.js +22 -1
  46. package/dist/src/common/tencentClient/scfOperations.js +255 -133
  47. package/dist/src/common/tencentClient/tdsqlcClusterMapper.js +81 -0
  48. package/dist/src/common/tencentClient/tdsqlcOperations.js +93 -99
  49. package/dist/src/common/triggerMapper.js +36 -0
  50. package/dist/src/common/volcengineClient/apigwOperations.js +539 -159
  51. package/dist/src/common/volcengineClient/iamOperations.js +58 -48
  52. package/dist/src/common/volcengineClient/index.js +46 -21
  53. package/dist/src/common/volcengineClient/stsOperations.js +32 -0
  54. package/dist/src/common/volcengineClient/tlsOperations.js +229 -178
  55. package/dist/src/common/volcengineClient/tosOperations.js +78 -19
  56. package/dist/src/common/volcengineClient/vefaasOperations.js +272 -54
  57. package/dist/src/lang/en.js +84 -0
  58. package/dist/src/lang/zh-CN.js +84 -0
  59. package/dist/src/parser/eventParser.js +2 -0
  60. package/dist/src/parser/functionParser.js +96 -65
  61. package/dist/src/parser/index.js +7 -4
  62. package/dist/src/stack/aliyunStack/apigwExecutor.js +39 -1
  63. package/dist/src/stack/aliyunStack/apigwPlanner.js +14 -10
  64. package/dist/src/stack/aliyunStack/apigwResource.js +216 -124
  65. package/dist/src/stack/aliyunStack/apigwTypes.js +16 -3
  66. package/dist/src/stack/aliyunStack/databaseExecutor.js +39 -1
  67. package/dist/src/stack/aliyunStack/databasePlanner.js +13 -1
  68. package/dist/src/stack/aliyunStack/databaseResource.js +135 -40
  69. package/dist/src/stack/aliyunStack/deployer.js +2 -2
  70. package/dist/src/stack/aliyunStack/destroyer.js +2 -2
  71. package/dist/src/stack/aliyunStack/fc3Executor.js +25 -2
  72. package/dist/src/stack/aliyunStack/fc3Planner.js +11 -1
  73. package/dist/src/stack/aliyunStack/fc3Resource.js +327 -64
  74. package/dist/src/stack/aliyunStack/ossExecutor.js +39 -1
  75. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  76. package/dist/src/stack/aliyunStack/ossResource.js +267 -219
  77. package/dist/src/stack/aliyunStack/tablestoreExecutor.js +39 -1
  78. package/dist/src/stack/aliyunStack/tablestorePlanner.js +13 -1
  79. package/dist/src/stack/aliyunStack/tablestoreResource.js +54 -20
  80. package/dist/src/stack/alreadyExists.js +26 -0
  81. package/dist/src/stack/ownershipTag.js +40 -0
  82. package/dist/src/stack/rfsStack/index.js +3 -1
  83. package/dist/src/stack/scfStack/cosExecutor.js +39 -1
  84. package/dist/src/stack/scfStack/cosPlanner.js +11 -1
  85. package/dist/src/stack/scfStack/cosResource.js +167 -64
  86. package/dist/src/stack/scfStack/deployer.js +2 -2
  87. package/dist/src/stack/scfStack/destroyer.js +2 -2
  88. package/dist/src/stack/scfStack/esServerlessExecutor.js +39 -1
  89. package/dist/src/stack/scfStack/esServerlessPlanner.js +11 -1
  90. package/dist/src/stack/scfStack/esServerlessResource.js +88 -23
  91. package/dist/src/stack/scfStack/scfExecutor.js +39 -1
  92. package/dist/src/stack/scfStack/scfPlanner.js +12 -2
  93. package/dist/src/stack/scfStack/scfResource.js +484 -14
  94. package/dist/src/stack/scfStack/tdsqlcExecutor.js +39 -1
  95. package/dist/src/stack/scfStack/tdsqlcPlanner.js +12 -1
  96. package/dist/src/stack/scfStack/tdsqlcResource.js +95 -16
  97. package/dist/src/stack/scfStack/tdsqlcTypes.js +5 -1
  98. package/dist/src/stack/volcengineStack/apigwExecutor.js +39 -1
  99. package/dist/src/stack/volcengineStack/apigwPlanner.js +25 -53
  100. package/dist/src/stack/volcengineStack/apigwResource.js +418 -222
  101. package/dist/src/stack/volcengineStack/apigwTypes.js +76 -66
  102. package/dist/src/stack/volcengineStack/deployer.js +49 -14
  103. package/dist/src/stack/volcengineStack/destroyer.js +1 -1
  104. package/dist/src/stack/volcengineStack/index.js +1 -2
  105. package/dist/src/stack/volcengineStack/tosExecutor.js +25 -2
  106. package/dist/src/stack/volcengineStack/tosPlanner.js +11 -1
  107. package/dist/src/stack/volcengineStack/tosResource.js +82 -27
  108. package/dist/src/stack/volcengineStack/tosTypes.js +12 -0
  109. package/dist/src/stack/volcengineStack/vefaasExecutor.js +25 -2
  110. package/dist/src/stack/volcengineStack/vefaasPlanner.js +71 -2
  111. package/dist/src/stack/volcengineStack/vefaasResource.js +148 -98
  112. package/dist/src/stack/volcengineStack/vefaasTypes.js +1 -3
  113. package/dist/src/types/domains/backend.js +1 -0
  114. package/dist/src/types/domains/state.js +29 -1
  115. package/dist/src/validator/eventSchema.js +10 -0
  116. package/dist/src/validator/functionSchema.js +37 -12
  117. package/dist/src/validator/iacSchema.js +1 -0
  118. package/dist/tsconfig.tsbuildinfo +1 -1
  119. package/package.json +3 -1
@@ -1,302 +1,498 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.deleteApigwResource = exports.updateApigwResource = exports.readApigwResourceByName = exports.readApigwResource = exports.createApigwResource = void 0;
3
+ exports.deleteApigwResource = exports.updateApigwResource = exports.createApigwResource = void 0;
4
+ const types_1 = require("../../types");
4
5
  const volcengineClient_1 = require("../../common/volcengineClient");
5
6
  const apigwTypes_1 = require("./apigwTypes");
6
7
  const stateManager_1 = require("../../common/stateManager");
7
8
  const common_1 = require("../../common");
8
9
  const logger_1 = require("../../common/logger");
9
10
  const lang_1 = require("../../lang");
10
- const buildApigwGroupInstanceFromProvider = (info, stage) => {
11
- return {
12
- type: 'VOLCENGINE_APIGW_GROUP',
13
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, info.gatewayId ?? ''),
14
- id: info.gatewayId ?? '',
15
- gatewayId: info.gatewayId ?? null,
16
- gatewayName: info.gatewayName ?? null,
17
- description: info.description ?? null,
18
- protocol: info.protocol ?? null,
19
- status: info.status ?? null,
20
- createdTime: info.createdTime ?? null,
21
- subDomain: info.subDomain ?? null,
22
- };
23
- };
24
- const buildApigwApiInstanceFromProvider = (info, stage, gatewayId) => {
11
+ const ownershipTag_1 = require("../ownershipTag");
12
+ const alreadyExists_1 = require("../alreadyExists");
13
+ const buildGatewayInstance = (info, stage) => ({
14
+ type: 'VOLCENGINE_APIGW_GATEWAY',
15
+ sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, info.gatewayId ?? ''),
16
+ id: info.gatewayId ?? '',
17
+ gatewayId: info.gatewayId ?? null,
18
+ gatewayName: info.gatewayName ?? null,
19
+ status: info.status ?? null,
20
+ gatewayType: info.type ?? null,
21
+ createdTime: info.createdTime ?? null,
22
+ description: info.description ?? null,
23
+ message: info.message ?? null,
24
+ tags: info.tags ?? null,
25
+ region: info.region ?? null,
26
+ version: info.version ?? null,
27
+ projectName: info.projectName ?? null,
28
+ networkSpec: info.networkSpec ?? null,
29
+ backendSpec: info.backendSpec ?? null,
30
+ monitorSpec: info.monitorSpec ?? null,
31
+ logSpec: info.logSpec ?? null,
32
+ resourceSpec: info.resourceSpec ?? null,
33
+ });
34
+ const ensureApigwLogResources = async (context, serviceName, existingInstances) => {
35
+ const client = (0, volcengineClient_1.createVolcengineClient)(context);
36
+ const tlsProjectInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_PROJECT');
37
+ const tlsTopicInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_TLS_TOPIC');
38
+ if (tlsProjectInstance && tlsTopicInstance) {
39
+ return {
40
+ projectId: tlsProjectInstance.projectId ?? '',
41
+ topicId: tlsTopicInstance.topicId ?? '',
42
+ instances: existingInstances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_')),
43
+ };
44
+ }
45
+ const projectName = `${serviceName}-${context.stage}-apigw-tls`;
46
+ const topicName = `${serviceName}-${context.stage}-apigw-logs`;
47
+ logger_1.logger.info(lang_1.lang.__('CREATING_TLS_PROJECT', { projectName }));
48
+ const project = await client.tls.createProject({
49
+ projectName,
50
+ description: `API Gateway access logs for ${serviceName}`,
51
+ region: context.region,
52
+ });
53
+ logger_1.logger.info(lang_1.lang.__('CREATING_TLS_TOPIC', { topicName }));
54
+ const topic = await client.tls.createTopic({
55
+ projectName,
56
+ topicName,
57
+ description: `API Gateway access logs for ${serviceName}`,
58
+ ttl: 30,
59
+ });
60
+ logger_1.logger.info(lang_1.lang.__('CREATING_TLS_INDEX', { topicName }));
61
+ await client.tls.createIndex({
62
+ projectName,
63
+ topicName,
64
+ fullTextIndex: {
65
+ delimiter: ' ,.?;!\n\t',
66
+ caseSensitive: false,
67
+ },
68
+ });
69
+ logger_1.logger.info(lang_1.lang.__('WAITING_FOR_TLS_RESOURCES', { projectName, topicName }));
70
+ await client.tls.waitForProject(projectName);
71
+ await client.tls.waitForTopic(projectName, topicName);
25
72
  return {
26
- type: 'VOLCENGINE_APIGW_API',
27
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, `${gatewayId}/${info.apiId}`),
28
- id: info.apiId ?? '',
29
- apiId: info.apiId ?? null,
30
- apiName: info.apiName ?? null,
31
- gatewayId: info.gatewayId ?? null,
32
- method: info.method ?? null,
33
- path: info.path ?? null,
34
- description: info.description ?? null,
35
- backendType: info.backendType ?? null,
36
- backendFunctionName: info.backendFunctionName ?? null,
37
- status: info.status ?? null,
38
- createdTime: info.createdTime ?? null,
73
+ projectId: project.projectId ?? '',
74
+ topicId: topic.topicId ?? '',
75
+ instances: [
76
+ {
77
+ type: 'VOLCENGINE_TLS_PROJECT',
78
+ sid: (0, common_1.buildSid)('volcengine', 'tls', context.stage, projectName),
79
+ id: projectName,
80
+ projectId: project.projectId ?? '',
81
+ ...project,
82
+ },
83
+ {
84
+ type: 'VOLCENGINE_TLS_TOPIC',
85
+ sid: (0, common_1.buildSid)('volcengine', 'tls', context.stage, `${projectName}/${topicName}`),
86
+ id: `${projectName}/${topicName}`,
87
+ projectId: project.projectId ?? '',
88
+ topicId: topic.topicId ?? '',
89
+ ...topic,
90
+ },
91
+ ],
39
92
  };
40
93
  };
41
- const buildApigwDeploymentInstance = (gatewayId, apiId, stageName, stage) => {
42
- return {
43
- type: 'VOLCENGINE_APIGW_DEPLOYMENT',
44
- sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, `${gatewayId}/${apiId}/${stageName}`),
45
- id: `${gatewayId}/${apiId}/${stageName}`,
46
- gatewayId,
47
- apiId,
48
- stageName,
49
- };
94
+ const buildServiceInstance = (serviceId, serviceName, gatewayId, stage, info) => ({
95
+ type: 'VOLCENGINE_APIGW_SERVICE',
96
+ sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, serviceId),
97
+ id: serviceId,
98
+ serviceId,
99
+ serviceName,
100
+ gatewayId,
101
+ ...(info?.status && { status: info.status }),
102
+ ...(info?.protocol && { protocol: info.protocol }),
103
+ ...(info?.createdTime && { createdTime: info.createdTime }),
104
+ ...(info?.gatewayName && { gatewayName: info.gatewayName }),
105
+ ...(info?.message && { message: info.message }),
106
+ ...(info?.comments && { comments: info.comments }),
107
+ ...(info?.authSpec && { authSpec: info.authSpec }),
108
+ ...(info?.domains && { domains: info.domains }),
109
+ ...(info?.customDomains && { customDomains: info.customDomains }),
110
+ });
111
+ const buildUpstreamInstance = (upstreamId, upstreamName, gatewayId, functionId, stage, info) => ({
112
+ type: 'VOLCENGINE_APIGW_UPSTREAM',
113
+ sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, upstreamId),
114
+ id: upstreamId,
115
+ upstreamId,
116
+ upstreamName,
117
+ gatewayId,
118
+ functionId,
119
+ ...(info?.sourceType && { sourceType: info.sourceType }),
120
+ ...(info?.protocol && { protocol: info.protocol }),
121
+ ...(info?.status && { status: info.status }),
122
+ ...(info?.createdTime && { createdTime: info.createdTime }),
123
+ ...(info?.comments && { comments: info.comments }),
124
+ ...(info?.resourceType && { resourceType: info.resourceType }),
125
+ ...(info?.updateTime && { updateTime: info.updateTime }),
126
+ ...(info?.backendTargetList && { backendTargetList: info.backendTargetList }),
127
+ });
128
+ const buildRouteInstance = (routeId, routeName, serviceId, stage, info) => ({
129
+ type: 'VOLCENGINE_APIGW_ROUTE',
130
+ sid: (0, common_1.buildSid)('volcengine', 'apigw', stage, routeId),
131
+ id: routeId,
132
+ routeId,
133
+ routeName,
134
+ serviceId,
135
+ ...(info?.method && { method: info.method }),
136
+ ...(info?.path && { path: info.path }),
137
+ ...(info?.upstreamIds && { upstreamIds: info.upstreamIds }),
138
+ ...(info?.status && { status: info.status }),
139
+ ...(info?.enable !== undefined && { enable: info.enable }),
140
+ ...(info?.priority !== undefined && { priority: info.priority }),
141
+ ...(info?.matchRule && { matchRule: info.matchRule }),
142
+ ...(info?.upstreamList && { upstreamList: info.upstreamList }),
143
+ });
144
+ /**
145
+ * Resolve the veFaaS function Id for a ${functions.xxx} backend ref from state.
146
+ * The function resource must already be deployed (functions deploy before events).
147
+ */
148
+ const resolveFunctionIdFromState = (state, backendRef) => {
149
+ const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
150
+ const fnState = (0, stateManager_1.getResource)(state, `functions.${fnKey}`);
151
+ const instance = fnState?.instances?.find((i) => i.type === 'VOLCENGINE_VEFAAS_FUNCTION');
152
+ const functionId = instance?.functionId;
153
+ if (!functionId) {
154
+ throw new Error(`Cannot resolve veFaaS function Id for backend ${backendRef} (functions.${fnKey} has no functionId in state). Deploy the function first.`);
155
+ }
156
+ return functionId;
50
157
  };
51
158
  const createApigwResource = async (context, event, serviceName, state) => {
52
159
  const logicalId = `events.${event.key}`;
53
160
  const client = (0, volcengineClient_1.createVolcengineClient)(context);
54
- const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
55
- let gatewayId;
56
- try {
57
- const existingGateway = await client.apigw.findGatewayByName(groupConfig.groupName);
58
- if (existingGateway?.gatewayId) {
59
- logger_1.logger.info(lang_1.lang.__('APIGW_GROUP_FOUND_REUSING', { groupName: groupConfig.groupName }));
60
- gatewayId = existingGateway.gatewayId;
161
+ const gatewayConfig = (0, apigwTypes_1.eventToApigwGatewayConfig)(event, serviceName, context.stage, (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId));
162
+ // The serverless gateway is account-scoped (one per account per region) —
163
+ // reuse an existing one (ours or already present) instead of creating another.
164
+ let gatewayInfo = await client.apigw.findServerlessGateway();
165
+ if (!gatewayInfo?.gatewayId) {
166
+ const existingByName = await client.apigw.findGatewayByName(gatewayConfig.gatewayName);
167
+ if (existingByName?.gatewayId && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, existingByName.tags)) {
168
+ gatewayInfo = existingByName;
61
169
  }
62
- else {
63
- const gatewayInfo = await client.apigw.createGateway(groupConfig);
64
- gatewayId = gatewayInfo.gatewayId;
170
+ }
171
+ if (!gatewayInfo?.gatewayId) {
172
+ // NetworkSpec (vpc_id + subnet_ids) is required by CreateGateway for all
173
+ // types — verified live: omitting it returns "missing NetworkSpec".
174
+ if (!gatewayConfig.network) {
175
+ throw new Error(`events.${event.key}: network (vpc_id + subnet_ids) is required to create the API Gateway instance — add it to the event config`);
176
+ }
177
+ try {
178
+ gatewayInfo = await client.apigw.createGateway(gatewayConfig);
179
+ }
180
+ catch (error) {
181
+ if ((0, alreadyExists_1.isResourceAlreadyExistsError)(error)) {
182
+ const probe = (await client.apigw.findGatewayByName(gatewayConfig.gatewayName)) ??
183
+ (await client.apigw.findServerlessGateway());
184
+ if (probe?.gatewayId && (0, ownershipTag_1.isOwnedByStack)(context, logicalId, probe.tags)) {
185
+ gatewayInfo = probe;
186
+ }
187
+ else {
188
+ throw new types_1.PartialResourceError(state, new Error(`API Gateway ${gatewayConfig.gatewayName} already exists but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to adopt — resolve manually.`));
189
+ }
190
+ }
191
+ else {
192
+ throw error;
193
+ }
65
194
  }
66
195
  }
67
- catch (error) {
68
- logger_1.logger.debug(`Could not find existing gateway, creating new: ${error}`);
69
- const gatewayInfo = await client.apigw.createGateway(groupConfig);
70
- gatewayId = gatewayInfo.gatewayId;
196
+ if (!gatewayInfo?.gatewayId) {
197
+ throw new Error('Failed to create or reuse an API Gateway instance');
71
198
  }
72
- const gatewayInfo = await client.apigw.getGateway(gatewayId);
73
- if (!gatewayInfo) {
74
- throw new Error(`Failed to get API Gateway info after creation: ${gatewayId}`);
199
+ const gatewayId = gatewayInfo.gatewayId;
200
+ // Gateway creation is async — service/upstream/route calls are rejected
201
+ // until the instance reaches Running.
202
+ gatewayInfo = await client.apigw.waitForGatewayRunning(gatewayId);
203
+ const instances = [buildGatewayInstance(gatewayInfo, context.stage)];
204
+ if (event.log) {
205
+ const logResources = await ensureApigwLogResources(context, serviceName, []);
206
+ await client.apigw.updateGatewayLog(gatewayId, {
207
+ enable: true,
208
+ projectId: logResources.projectId,
209
+ topicId: logResources.topicId,
210
+ });
211
+ instances.push(...logResources.instances);
75
212
  }
76
- const instances = [
77
- buildApigwGroupInstanceFromProvider(gatewayInfo, context.stage),
78
- ];
79
- const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
213
+ const serviceConfig = (0, apigwTypes_1.eventToApigwServiceConfig)(event, serviceName, context.stage, gatewayId);
214
+ let serviceId;
215
+ const existingService = await client.apigw.findServiceByName(gatewayId, serviceConfig.serviceName);
216
+ if (existingService?.serviceId) {
217
+ serviceId = existingService.serviceId;
218
+ }
219
+ else {
220
+ serviceId = await client.apigw.createService(serviceConfig);
221
+ }
222
+ // Refresh the full service record — the create response carries only the Id
223
+ // and findServiceByName may return a partial read; getService returns the
224
+ // complete provider detail (status/protocol/createdTime/…).
225
+ const serviceInfo = (await client.apigw.getService(serviceId).catch(() => null)) ?? existingService ?? null;
226
+ instances.push(buildServiceInstance(serviceId, serviceConfig.serviceName, gatewayId, context.stage, serviceInfo ?? undefined));
80
227
  const partialResourceState = {
81
228
  mode: 'managed',
82
229
  region: context.region,
83
- definition: {
84
- ...groupDefinition,
85
- triggers: event.triggers.map((t) => ({
86
- method: t.method,
87
- path: t.path,
88
- backend: t.backend,
89
- })),
90
- domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
91
- },
230
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
92
231
  instances,
232
+ status: 'tainted',
93
233
  lastUpdated: new Date().toISOString(),
94
234
  };
95
- state = (0, stateManager_1.setResource)(state, logicalId, partialResourceState);
96
- for (const trigger of event.triggers) {
97
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, gatewayId, serviceName, context.region, context.stage);
98
- const apiId = await client.apigw.createApi(apiConfig);
99
- const apiInfo = await client.apigw.getApi(gatewayId, apiId);
100
- if (apiInfo) {
101
- instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.stage, gatewayId));
235
+ const stateAfterDependents = (0, stateManager_1.setResource)(state, logicalId, partialResourceState);
236
+ try {
237
+ // One upstream per backend function (triggers sharing a function reuse it).
238
+ const upstreamByFunction = new Map();
239
+ for (const trigger of event.triggers) {
240
+ const backendRef = String(trigger.backend);
241
+ const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
242
+ let upstreamId = upstreamByFunction.get(fnKey);
243
+ if (!upstreamId) {
244
+ const functionId = resolveFunctionIdFromState(state, backendRef);
245
+ const upstreamName = `${event.name}-${context.stage}-upstream-${fnKey.replace(/_/g, '-')}`;
246
+ const existingUpstream = await client.apigw.findUpstreamByName(gatewayId, upstreamName);
247
+ if (existingUpstream?.upstreamId) {
248
+ upstreamId = existingUpstream.upstreamId;
249
+ }
250
+ else {
251
+ const upstreamConfig = (0, apigwTypes_1.triggerToApigwUpstreamConfig)(event, trigger, serviceName, context.stage, gatewayId, functionId);
252
+ upstreamId = await client.apigw.createUpstream(upstreamConfig);
253
+ }
254
+ upstreamByFunction.set(fnKey, upstreamId);
255
+ // Refresh the full upstream record — the create response carries only
256
+ // the Id; getUpstream returns status/sourceType/protocol/createdTime/…
257
+ // for both the create and adopt paths.
258
+ const upstreamInfo = (await client.apigw.getUpstream(upstreamId).catch(() => null)) ??
259
+ existingUpstream ??
260
+ null;
261
+ instances.push(buildUpstreamInstance(upstreamId, upstreamName, gatewayId, functionId, context.stage, upstreamInfo ?? undefined));
262
+ }
263
+ const routeConfig = (0, apigwTypes_1.triggerToApigwRouteConfig)(event, trigger, serviceId, upstreamId);
264
+ const routeId = await client.apigw.createRoute(routeConfig);
265
+ const routeInfo = {
266
+ routeId,
267
+ routeName: routeConfig.routeName,
268
+ serviceId,
269
+ method: routeConfig.method,
270
+ path: routeConfig.path,
271
+ upstreamIds: [routeConfig.upstreamId],
272
+ };
273
+ instances.push(buildRouteInstance(routeId, routeConfig.routeName, serviceId, context.stage, routeInfo));
102
274
  }
103
- await client.apigw.deployApi(gatewayId, apiId);
104
- instances.push(buildApigwDeploymentInstance(gatewayId, apiId, 'RELEASE', context.stage));
105
- const updatedResourceState = {
106
- mode: 'managed',
107
- region: context.region,
108
- definition: {
109
- ...groupDefinition,
110
- triggers: event.triggers.map((t) => ({
111
- method: t.method,
112
- path: t.path,
113
- backend: t.backend,
114
- })),
115
- domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
116
- },
117
- instances,
118
- lastUpdated: new Date().toISOString(),
119
- };
120
- state = (0, stateManager_1.setResource)(state, logicalId, updatedResourceState);
121
- }
122
- if (event.domain) {
123
- try {
124
- const domainConfig = {
125
- gatewayId,
126
- domainName: event.domain.domain_name,
275
+ if (event.domain) {
276
+ const domainName = event.domain.domain_name;
277
+ const domainId = await client.apigw.createCustomDomain({
278
+ serviceId,
279
+ domainName,
127
280
  certificateId: event.domain.certificate_id,
128
- };
129
- await client.apigw.bindDomain(domainConfig);
281
+ });
282
+ instances.push({
283
+ type: 'VOLCENGINE_APIGW_DOMAIN',
284
+ sid: (0, common_1.buildSid)('volcengine', 'apigw', context.stage, domainId || domainName),
285
+ id: domainId || domainName,
286
+ domainName,
287
+ serviceId,
288
+ });
130
289
  }
131
- catch (error) {
132
- logger_1.logger.error(lang_1.lang.__('APIGW_DOMAIN_BINDING_FAILED', { error: String(error) }));
133
- logger_1.logger.info(lang_1.lang.__('APIGW_GROUP_APIS_CREATED_DOMAIN_FAILED'));
134
- logger_1.logger.info(lang_1.lang.__('APIGW_STATE_SAVED_RETRY'));
135
- return state;
290
+ }
291
+ catch (error) {
292
+ if (error instanceof types_1.PartialResourceError) {
293
+ throw error;
136
294
  }
295
+ throw new types_1.PartialResourceError(stateAfterDependents, error instanceof Error ? error : new Error(String(error)));
137
296
  }
138
297
  const finalResourceState = {
139
298
  mode: 'managed',
140
299
  region: context.region,
141
- definition: {
142
- ...groupDefinition,
143
- triggers: event.triggers.map((t) => ({
144
- method: t.method,
145
- path: t.path,
146
- backend: t.backend,
147
- })),
148
- domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
149
- },
300
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
150
301
  instances,
302
+ status: 'ready',
151
303
  lastUpdated: new Date().toISOString(),
152
304
  };
153
- return (0, stateManager_1.setResource)(state, logicalId, finalResourceState);
305
+ return (0, stateManager_1.setResource)(stateAfterDependents, logicalId, finalResourceState);
154
306
  };
155
307
  exports.createApigwResource = createApigwResource;
156
- const readApigwResource = async (context, gatewayId) => {
157
- const client = (0, volcengineClient_1.createVolcengineClient)(context);
158
- return await client.apigw.getGateway(gatewayId);
159
- };
160
- exports.readApigwResource = readApigwResource;
161
- const readApigwResourceByName = async (context, gatewayName) => {
162
- const client = (0, volcengineClient_1.createVolcengineClient)(context);
163
- return await client.apigw.findGatewayByName(gatewayName);
164
- };
165
- exports.readApigwResourceByName = readApigwResourceByName;
166
308
  const updateApigwResource = async (context, event, serviceName, state) => {
167
- const logicalId = `events.${event.key}`;
168
- const existingState = (0, stateManager_1.getResource)(state, logicalId);
169
- const client = (0, volcengineClient_1.createVolcengineClient)(context);
309
+ const existingState = (0, stateManager_1.getResource)(state, `events.${event.key}`);
170
310
  if (!existingState) {
171
311
  return (0, exports.createApigwResource)(context, event, serviceName, state);
172
312
  }
173
- const existingInstances = existingState.instances;
174
- const groupInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_APIGW_GROUP');
175
- if (!groupInstance) {
313
+ const client = (0, volcengineClient_1.createVolcengineClient)(context);
314
+ const serviceInstance = existingState.instances.find((i) => i.type === 'VOLCENGINE_APIGW_SERVICE');
315
+ if (!serviceInstance) {
176
316
  return (0, exports.createApigwResource)(context, event, serviceName, state);
177
317
  }
178
- const gatewayId = groupInstance.id;
179
- const groupConfig = (0, apigwTypes_1.eventToApigwGroupConfig)(event, serviceName, context.stage);
180
- await client.apigw.updateGateway(gatewayId, groupConfig);
181
- const gatewayInfo = await client.apigw.getGateway(gatewayId);
182
- if (!gatewayInfo) {
183
- throw new Error(`Failed to get API Gateway info after update: ${gatewayId}`);
184
- }
185
- const instances = [
186
- buildApigwGroupInstanceFromProvider(gatewayInfo, context.stage),
187
- ];
188
- const existingApis = existingInstances.filter((i) => i.type === 'VOLCENGINE_APIGW_API');
189
- const neededApiKeys = new Set();
190
- for (const trigger of event.triggers) {
191
- const apiConfig = (0, apigwTypes_1.triggerToApigwApiConfig)(event, trigger, gatewayId, serviceName, context.region, context.stage);
192
- const apiKey = (0, apigwTypes_1.generateApiKey)(trigger.method, trigger.path);
193
- neededApiKeys.add(apiKey);
194
- const existingApi = existingApis.find((a) => {
195
- return a.id && a.apiName === apiConfig.apiName;
196
- });
197
- let apiId;
198
- if (existingApi) {
199
- apiId = existingApi.id;
200
- await client.apigw.updateApi(apiId, apiConfig);
318
+ const serviceId = serviceInstance.id;
319
+ const existingRoutes = existingState.instances.filter((i) => i.type === 'VOLCENGINE_APIGW_ROUTE');
320
+ const existingUpstreams = existingState.instances.filter((i) => i.type === 'VOLCENGINE_APIGW_UPSTREAM');
321
+ const neededRouteIds = new Set();
322
+ const instances = existingState.instances.filter((i) => i.type === 'VOLCENGINE_APIGW_GATEWAY' ||
323
+ i.type === 'VOLCENGINE_APIGW_SERVICE' ||
324
+ i.type === 'VOLCENGINE_APIGW_UPSTREAM' ||
325
+ i.type.startsWith('VOLCENGINE_TLS_'));
326
+ try {
327
+ if (event.log) {
328
+ const logResources = await ensureApigwLogResources(context, serviceName, existingState.instances);
329
+ await client.apigw.updateGatewayLog(serviceInstance.gatewayId, {
330
+ enable: true,
331
+ projectId: logResources.projectId,
332
+ topicId: logResources.topicId,
333
+ });
334
+ instances.push(...logResources.instances);
201
335
  }
202
336
  else {
203
- apiId = await client.apigw.createApi(apiConfig);
337
+ const existingLogResources = existingState.instances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_'));
338
+ if (existingLogResources.length > 0) {
339
+ await client.apigw.updateGatewayLog(serviceInstance.gatewayId, {
340
+ enable: false,
341
+ projectId: '',
342
+ topicId: '',
343
+ });
344
+ }
204
345
  }
205
- const apiInfo = await client.apigw.getApi(gatewayId, apiId);
206
- if (apiInfo) {
207
- instances.push(buildApigwApiInstanceFromProvider(apiInfo, context.stage, gatewayId));
346
+ const upstreamByFunction = new Map();
347
+ for (const upstream of existingUpstreams) {
348
+ const fnKey = upstream.functionId
349
+ ? String(upstream.functionId)
350
+ : '';
351
+ if (fnKey)
352
+ upstreamByFunction.set(fnKey, upstream.id);
208
353
  }
209
- await client.apigw.deployApi(gatewayId, apiId);
210
- instances.push(buildApigwDeploymentInstance(gatewayId, apiId, 'RELEASE', context.stage));
211
- }
212
- for (const existingApi of existingApis) {
213
- const apiInfo = await client.apigw.getApi(gatewayId, existingApi.id);
214
- if (apiInfo) {
215
- const isNeeded = event.triggers.some((t) => {
216
- const expectedName = (0, apigwTypes_1.triggerToApigwApiConfig)(event, t, gatewayId, serviceName, context.region, context.stage).apiName;
217
- return apiInfo.apiName === expectedName;
218
- });
219
- if (!isNeeded) {
220
- await client.apigw.deleteApi(gatewayId, existingApi.id);
354
+ for (const trigger of event.triggers) {
355
+ const backendRef = String(trigger.backend);
356
+ const fnKey = (0, apigwTypes_1.resolveFunctionKey)(backendRef);
357
+ const functionId = resolveFunctionIdFromState(state, backendRef);
358
+ let upstreamId = upstreamByFunction.get(functionId);
359
+ if (!upstreamId) {
360
+ const upstreamName = `${event.name}-${context.stage}-upstream-${fnKey.replace(/_/g, '-')}`;
361
+ const existing = await client.apigw.findUpstreamByName(serviceInstance.gatewayId, upstreamName);
362
+ if (existing?.upstreamId) {
363
+ upstreamId = existing.upstreamId;
364
+ }
365
+ else {
366
+ const upstreamConfig = (0, apigwTypes_1.triggerToApigwUpstreamConfig)(event, trigger, serviceName, context.stage, serviceInstance.gatewayId, functionId);
367
+ upstreamId = await client.apigw.createUpstream(upstreamConfig);
368
+ }
369
+ upstreamByFunction.set(functionId, upstreamId);
221
370
  }
371
+ const routeConfig = (0, apigwTypes_1.triggerToApigwRouteConfig)(event, trigger, serviceId, upstreamId);
372
+ // Routes are not idempotent on the provider: CreateRoute with an
373
+ // existing Name fails with DuplicatedResource.Route. Mirror the upstream
374
+ // adopt-or-create pattern — reuse a same-named remote route when present
375
+ // so re-running a deploy (or resuming after a partial failure) converges.
376
+ const existing = await client.apigw.findRouteByName(serviceId, routeConfig.routeName);
377
+ const routeId = existing?.routeId ?? (await client.apigw.createRoute(routeConfig));
378
+ neededRouteIds.add(routeId);
379
+ const routeInfo = existing ?? {
380
+ routeId,
381
+ routeName: routeConfig.routeName,
382
+ serviceId,
383
+ method: routeConfig.method,
384
+ path: routeConfig.path,
385
+ upstreamIds: [routeConfig.upstreamId],
386
+ };
387
+ instances.push(buildRouteInstance(routeId, routeConfig.routeName, serviceId, context.stage, routeInfo));
222
388
  }
223
- }
224
- if (event.domain) {
225
- const domainConfig = {
226
- gatewayId,
227
- domainName: event.domain.domain_name,
228
- certificateId: event.domain.certificate_id,
229
- };
230
- await client.apigw.bindDomain(domainConfig);
231
- }
232
- else {
233
- const existingDomain = existingState.definition?.domain;
234
- if (existingDomain?.domainName) {
235
- const previousDomain = existingDomain.domainName;
236
- try {
237
- await client.apigw.unbindDomain(gatewayId, previousDomain);
238
- }
239
- catch (error) {
240
- logger_1.logger.warn(lang_1.lang.__('APIGW_DOMAIN_UNBIND_FAILED', { domain: previousDomain, error: String(error) }));
389
+ // Remove routes no longer in the desired set.
390
+ for (const existingRoute of existingRoutes) {
391
+ if (!neededRouteIds.has(existingRoute.id)) {
392
+ await client.apigw.deleteRoute(existingRoute.id);
241
393
  }
242
394
  }
243
395
  }
244
- const groupDefinition = (0, apigwTypes_1.extractApigwGroupDefinition)(groupConfig);
396
+ catch (error) {
397
+ throw new types_1.PartialResourceError(state, error instanceof Error ? error : new Error(String(error)));
398
+ }
245
399
  const resourceState = {
246
400
  mode: 'managed',
247
401
  region: context.region,
248
- definition: {
249
- ...groupDefinition,
250
- triggers: event.triggers.map((t) => ({
251
- method: t.method,
252
- path: t.path,
253
- backend: t.backend,
254
- })),
255
- domain: (0, apigwTypes_1.extractEventDomainDefinition)(event.domain),
256
- },
402
+ definition: (0, apigwTypes_1.buildEventResourceDefinition)(event),
257
403
  instances,
258
404
  lastUpdated: new Date().toISOString(),
259
405
  };
260
- return (0, stateManager_1.setResource)(state, logicalId, resourceState);
406
+ return (0, stateManager_1.setResource)(state, `events.${event.key}`, resourceState);
261
407
  };
262
408
  exports.updateApigwResource = updateApigwResource;
263
409
  const deleteApigwResource = async (context, logicalId, state) => {
264
410
  const existingState = (0, stateManager_1.getResource)(state, logicalId);
265
- const client = (0, volcengineClient_1.createVolcengineClient)(context);
266
411
  if (!existingState) {
267
412
  return state;
268
413
  }
269
- const existingInstances = existingState.instances;
270
- const groupInstance = existingInstances.find((i) => i.type === 'VOLCENGINE_APIGW_GROUP');
271
- if (!groupInstance) {
272
- return (0, stateManager_1.removeResource)(state, logicalId);
273
- }
274
- const gatewayId = groupInstance.id;
275
- const existingDomain = existingState.definition?.domain;
276
- if (existingDomain?.domainName) {
277
- const primaryDomain = existingDomain.domainName;
414
+ const client = (0, volcengineClient_1.createVolcengineClient)(context);
415
+ const serviceInstance = existingState.instances.find((i) => i.type === 'VOLCENGINE_APIGW_SERVICE');
416
+ const tlsInstances = existingState.instances.filter((i) => i.type.startsWith('VOLCENGINE_TLS_'));
417
+ if (tlsInstances.length > 0 && serviceInstance?.gatewayId) {
278
418
  try {
279
- await client.apigw.unbindDomain(gatewayId, primaryDomain);
419
+ await client.apigw.updateGatewayLog(serviceInstance.gatewayId, {
420
+ enable: false,
421
+ projectId: '',
422
+ topicId: '',
423
+ });
280
424
  }
281
425
  catch (error) {
282
- logger_1.logger.warn(lang_1.lang.__('APIGW_DOMAIN_UNBIND_FAILED', { domain: primaryDomain, error: String(error) }));
426
+ logger_1.logger.warn(lang_1.lang.__('APIGW_LOG_DISABLE_FAILED', {
427
+ gatewayId: String(serviceInstance.gatewayId),
428
+ error: String(error),
429
+ }));
430
+ }
431
+ for (const instance of [...tlsInstances].reverse()) {
432
+ try {
433
+ if (instance.type === 'VOLCENGINE_TLS_TOPIC') {
434
+ const [projectName, topicName] = instance.id.split('/');
435
+ logger_1.logger.info(lang_1.lang.__('DELETING_TLS_TOPIC', { id: instance.id }));
436
+ await client.tls.deleteTopic(projectName, topicName);
437
+ }
438
+ else if (instance.type === 'VOLCENGINE_TLS_PROJECT') {
439
+ logger_1.logger.info(lang_1.lang.__('DELETING_TLS_PROJECT', { id: instance.id }));
440
+ await client.tls.deleteProject(instance.id);
441
+ }
442
+ }
443
+ catch (error) {
444
+ logger_1.logger.warn(lang_1.lang.__('FAILED_TO_DELETE_RESOURCE', {
445
+ type: String(instance.type),
446
+ id: instance.id,
447
+ error: String(error),
448
+ }));
449
+ }
283
450
  }
284
451
  }
285
- const apis = existingInstances.filter((i) => i.type === 'VOLCENGINE_APIGW_API');
286
- for (const api of apis) {
452
+ if (serviceInstance) {
453
+ const routes = existingState.instances.filter((i) => i.type === 'VOLCENGINE_APIGW_ROUTE');
454
+ for (const route of routes) {
455
+ try {
456
+ await client.apigw.deleteRoute(route.id);
457
+ }
458
+ catch (error) {
459
+ const err = error;
460
+ if (err.code !== 'NotFound' && err.code !== 'RouteNotFound')
461
+ throw error;
462
+ }
463
+ }
464
+ const upstreams = existingState.instances.filter((i) => i.type === 'VOLCENGINE_APIGW_UPSTREAM');
465
+ for (const upstream of upstreams) {
466
+ try {
467
+ await client.apigw.deleteUpstream(upstream.id);
468
+ }
469
+ catch (error) {
470
+ const err = error;
471
+ if (err.code !== 'NotFound' && err.code !== 'UpstreamNotFound')
472
+ throw error;
473
+ }
474
+ }
287
475
  try {
288
- await client.apigw.deleteApi(gatewayId, api.id);
476
+ await client.apigw.deleteService(serviceInstance.id);
289
477
  }
290
- catch {
291
- // API might already be deleted
478
+ catch (error) {
479
+ const err = error;
480
+ if (err.code !== 'NotFound' && err.code !== 'ServiceNotFound')
481
+ throw error;
292
482
  }
293
483
  }
294
- try {
295
- await client.apigw.deleteGateway(gatewayId);
296
- }
297
- catch {
298
- // Gateway might already be deleted
484
+ const domainInstance = existingState.instances.find((i) => i.type === 'VOLCENGINE_APIGW_DOMAIN');
485
+ if (domainInstance?.id) {
486
+ try {
487
+ await client.apigw.deleteCustomDomain(domainInstance.id);
488
+ }
489
+ catch (error) {
490
+ const err = error;
491
+ if (err.code !== 'NotFound' && err.code !== 'DomainNotFound')
492
+ throw error;
493
+ }
299
494
  }
495
+ // The serverless gateway is account-scoped (one per region) — leave it in place.
300
496
  return (0, stateManager_1.removeResource)(state, logicalId);
301
497
  };
302
498
  exports.deleteApigwResource = deleteApigwResource;