@geek-fun/serverlessinsight 0.8.2 → 0.8.4

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