@geek-fun/serverlessinsight 0.9.2 → 0.9.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 (105) hide show
  1. package/.serverlessinsight/state-cdn-flow-app-cdn-flow-service.json.backup +1 -1
  2. package/.serverlessinsight/state-iam-test-app-iam-test-service.json.backup +2 -2
  3. package/.serverlessinsight/state-insight-poc-app-insight-poc-tencent.json.backup +4 -8
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +3 -8
  5. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +4 -4
  6. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  7. package/.serverlessinsight/state-insight-poc-timer-app-insight-poc-timer.json.backup +28 -5
  8. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +2 -2
  9. package/.serverlessinsight/state-insight-volc-nested-app-insight-volc-nested.json.backup +3 -3
  10. package/.serverlessinsight/state-nested-drift-app-nested-drift-service.json.backup +20 -5
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/AGENTS.md +10 -0
  13. package/CHANGELOG.md +62 -0
  14. package/README.md +256 -175
  15. package/README.zh-CN.md +249 -159
  16. package/dist/package.json +22 -19
  17. package/dist/src/commands/index.js +21 -52
  18. package/dist/src/commands/local.js +16 -3
  19. package/dist/src/commands/plan.js +35 -4
  20. package/dist/src/common/aliyunClient/apigwOperations.js +48 -9
  21. package/dist/src/common/aliyunClient/fc3Operations.js +7 -1
  22. package/dist/src/common/aliyunClient/ossOperations.js +214 -221
  23. package/dist/src/common/bucketPolicy.js +63 -0
  24. package/dist/src/common/domainUtils.js +4 -1
  25. package/dist/src/common/functionDefinition.js +25 -0
  26. package/dist/src/common/index.js +4 -0
  27. package/dist/src/common/jsonOutput.js +6 -1
  28. package/dist/src/common/nameBuilder.js +3 -1
  29. package/dist/src/common/planCapabilities.js +119 -0
  30. package/dist/src/common/planCompare.js +119 -66
  31. package/dist/src/common/planFormatter.js +22 -14
  32. package/dist/src/common/planRedaction.js +26 -0
  33. package/dist/src/common/refreshPlanner.js +66 -21
  34. package/dist/src/common/tencentClient/cosOperations.js +326 -322
  35. package/dist/src/common/tencentClient/scfOperations.js +9 -2
  36. package/dist/src/common/tencentClient/tdsqlcOperations.js +6 -11
  37. package/dist/src/common/triggerMapper.js +16 -1
  38. package/dist/src/common/volcengineClient/apigwOperations.js +82 -0
  39. package/dist/src/common/volcengineClient/iamOperations.js +27 -3
  40. package/dist/src/common/volcengineClient/tosOperations.js +62 -56
  41. package/dist/src/lang/en.js +33 -8
  42. package/dist/src/lang/index.js +28 -14
  43. package/dist/src/lang/zh-CN.js +33 -8
  44. package/dist/src/parser/eventParser.js +1 -0
  45. package/dist/src/parser/functionParser.js +1 -1
  46. package/dist/src/stack/aliyunStack/apigwDomainPlan.js +82 -0
  47. package/dist/src/stack/aliyunStack/apigwExecutor.js +4 -1
  48. package/dist/src/stack/aliyunStack/apigwPlanner.js +165 -25
  49. package/dist/src/stack/aliyunStack/apigwResource.js +172 -126
  50. package/dist/src/stack/aliyunStack/apigwTypes.js +3 -7
  51. package/dist/src/stack/aliyunStack/deployer.js +2 -0
  52. package/dist/src/stack/aliyunStack/esServerlessTypes.js +8 -4
  53. package/dist/src/stack/aliyunStack/fc3Executor.js +7 -3
  54. package/dist/src/stack/aliyunStack/fc3Planner.js +124 -155
  55. package/dist/src/stack/aliyunStack/fc3Resource.js +48 -52
  56. package/dist/src/stack/aliyunStack/fc3Types.js +30 -16
  57. package/dist/src/stack/aliyunStack/ossPlanner.js +15 -1
  58. package/dist/src/stack/aliyunStack/ossResource.js +113 -102
  59. package/dist/src/stack/aliyunStack/ossTypes.js +20 -20
  60. package/dist/src/stack/localStack/aliyunFc.js +1 -6
  61. package/dist/src/stack/localStack/event.js +31 -60
  62. package/dist/src/stack/localStack/function.js +24 -65
  63. package/dist/src/stack/localStack/functionRunner.js +10 -2
  64. package/dist/src/stack/localStack/httpAdapter.js +54 -0
  65. package/dist/src/stack/localStack/httpError.js +5 -0
  66. package/dist/src/stack/localStack/legacyLambda.js +26 -0
  67. package/dist/src/stack/localStack/localContext.js +29 -0
  68. package/dist/src/stack/localStack/localRoute.js +12 -0
  69. package/dist/src/stack/localStack/localRuntimes.js +22 -0
  70. package/dist/src/stack/localStack/localServer.js +8 -3
  71. package/dist/src/stack/localStack/requestBody.js +24 -0
  72. package/dist/src/stack/localStack/requestId.js +18 -0
  73. package/dist/src/stack/localStack/tencent.js +147 -0
  74. package/dist/src/stack/localStack/timer.js +23 -2
  75. package/dist/src/stack/localStack/volcengine.js +68 -0
  76. package/dist/src/stack/scfStack/cosPlanner.js +9 -14
  77. package/dist/src/stack/scfStack/cosResource.js +42 -50
  78. package/dist/src/stack/scfStack/cosTypes.js +19 -14
  79. package/dist/src/stack/scfStack/deployer.js +2 -0
  80. package/dist/src/stack/scfStack/scfExecutor.js +7 -3
  81. package/dist/src/stack/scfStack/scfHttpTrigger.js +106 -0
  82. package/dist/src/stack/scfStack/scfPlanner.js +67 -16
  83. package/dist/src/stack/scfStack/scfResource.js +170 -321
  84. package/dist/src/stack/scfStack/scfTypes.js +4 -3
  85. package/dist/src/stack/scfStack/tdsqlcPlanner.js +10 -13
  86. package/dist/src/stack/volcengineStack/apigwDomains.js +64 -0
  87. package/dist/src/stack/volcengineStack/apigwPlanner.js +71 -15
  88. package/dist/src/stack/volcengineStack/apigwResource.js +60 -24
  89. package/dist/src/stack/volcengineStack/apigwTypes.js +5 -1
  90. package/dist/src/stack/volcengineStack/deployer.js +6 -0
  91. package/dist/src/stack/volcengineStack/tosPlanner.js +8 -13
  92. package/dist/src/stack/volcengineStack/tosResource.js +22 -35
  93. package/dist/src/stack/volcengineStack/tosTypes.js +5 -8
  94. package/dist/src/stack/volcengineStack/vefaasPlanner.js +142 -49
  95. package/dist/src/stack/volcengineStack/vefaasResource.js +17 -12
  96. package/dist/src/stack/volcengineStack/vefaasTypes.js +6 -3
  97. package/dist/tsconfig.tsbuildinfo +1 -1
  98. package/package.json +22 -19
  99. package/release-notes.md +53 -0
  100. package/samples/README_TENCENT_COS.md +3 -3
  101. package/samples/README_TENCENT_SCF.md +3 -3
  102. package/samples/tencent-local/index.js +13 -0
  103. package/samples/tencent-local/serverlessinsight.yml +23 -0
  104. package/samples/volcengine-local/index.js +13 -0
  105. package/samples/volcengine-local/serverlessinsight.yml +28 -0
@@ -1,6 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateFunctionPlan = void 0;
4
+ const refreshPlanner_1 = require("../../common/refreshPlanner");
5
+ const fc3Types_1 = require("./fc3Types");
6
+ const triggerMapper_1 = require("../../common/triggerMapper");
4
7
  const common_1 = require("../../common");
5
8
  const aliyunClient_1 = require("../../common/aliyunClient");
6
9
  const ramOperations_1 = require("../../common/aliyunClient/ramOperations");
@@ -10,7 +13,7 @@ const refreshCache_1 = require("../../common/refreshCache");
10
13
  const planCompare_1 = require("../../common/planCompare");
11
14
  const concurrency_1 = require("../../common/concurrency");
12
15
  const siCron_1 = require("../../common/siCron");
13
- const fc3Types_1 = require("./fc3Types");
16
+ const fc3Types_2 = require("./fc3Types");
14
17
  const fc3Resource_1 = require("./fc3Resource");
15
18
  const lang_1 = require("../../lang");
16
19
  const ownershipTag_1 = require("../ownershipTag");
@@ -65,6 +68,27 @@ const resolveVpcConfigSecurityGroup = async (context, config) => {
65
68
  },
66
69
  };
67
70
  };
71
+ const removedFc3Dependents = (fn, currentState) => {
72
+ const recorded = (type) => currentState?.instances?.find((i) => i.type === type);
73
+ const recordedTimers = (currentState?.instances ?? []).filter((i) => i.type === 'ALIYUN_FC3_TIMER_TRIGGER');
74
+ return {
75
+ ...(!fn.triggers?.http && recorded('ALIYUN_FC3_HTTP_TRIGGER')
76
+ ? {
77
+ http: currentState?.definition?.http ?? recorded('ALIYUN_FC3_HTTP_TRIGGER')?.attributes ?? {},
78
+ }
79
+ : {}),
80
+ ...(!fn.domain && recorded('ALIYUN_FC3_CUSTOM_DOMAIN')
81
+ ? {
82
+ domain: currentState?.definition?.domain ?? {
83
+ domain_name: recorded('ALIYUN_FC3_CUSTOM_DOMAIN')?.id,
84
+ },
85
+ }
86
+ : {}),
87
+ ...(!fn.triggers?.timer && recordedTimers.length > 0
88
+ ? { timers: currentState?.definition?.timers ?? [] }
89
+ : {}),
90
+ };
91
+ };
68
92
  const planFunctionDeletion = (logicalId, definition) => ({
69
93
  logicalId,
70
94
  action: 'delete',
@@ -174,7 +198,8 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
174
198
  },
175
199
  ],
176
200
  };
177
- if (cloudTrust && !(0, common_1.attributesEqual)(cloudTrust, desiredTrust)) {
201
+ if (cloudTrust &&
202
+ (0, planCompare_1.remoteDiffersFromDesired)({ policy: JSON.stringify(cloudTrust) }, { policy: JSON.stringify(desiredTrust) })) {
178
203
  return 'PLAN_DRIFT_ROLE_POLICY';
179
204
  }
180
205
  // b. execution + custom policy (the `<roleName>-policy` custom document). An
@@ -185,7 +210,7 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
185
210
  const desiredPolicyDocument = parseRolePolicyDocument((0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
186
211
  if (!cloudPolicy ||
187
212
  !desiredPolicyDocument ||
188
- !(0, common_1.attributesEqual)(cloudPolicy, desiredPolicyDocument)) {
213
+ (0, planCompare_1.remoteDiffersFromDesired)({ policy: JSON.stringify(cloudPolicy) }, { policy: JSON.stringify(desiredPolicyDocument) })) {
189
214
  return 'PLAN_DRIFT_ROLE_POLICY';
190
215
  }
191
216
  // c. managed (system) policies as sorted name sets; desired ARNs strip the
@@ -193,7 +218,8 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
193
218
  const desiredManagedNames = (iamRole.managed_policies ?? []).map((policyArn) => policyArn.split('/').pop() ?? '');
194
219
  const cloudManagedNames = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.listAttachedRolePolicies:${roleName}`, () => client.ram.listAttachedRolePolicies(roleName));
195
220
  const asSortedSetKey = (names) => [...names].sort().join(',');
196
- if (asSortedSetKey(desiredManagedNames) !== asSortedSetKey(cloudManagedNames ?? [])) {
221
+ if (iamRole.managed_policies !== undefined &&
222
+ asSortedSetKey(desiredManagedNames) !== asSortedSetKey(cloudManagedNames ?? [])) {
197
223
  return 'PLAN_DRIFT_ROLE_POLICY';
198
224
  }
199
225
  return null;
@@ -205,6 +231,28 @@ const detectRolePolicyDrift = async (context, state, fn, currentState, roleName,
205
231
  * cannot shrink shards, so only a shard deficit counts as drift.
206
232
  * Returns an i18n drift-reason key (issue #246); null means no drift.
207
233
  */
234
+ const detectFunctionLifecycleDrift = async (context, client, fn) => {
235
+ const reasons = [];
236
+ if (fn.triggers?.http) {
237
+ const triggers = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.listTriggers:${fn.name}`, () => client.fc3.listTriggers(fn.name));
238
+ const trigger = (triggers ?? []).find((entry) => entry.triggerType === 'http' && entry.triggerName === 'http-trigger');
239
+ if (!trigger ||
240
+ (0, planCompare_1.remoteDiffersFromDesired)({ http: trigger.triggerConfig }, { http: (0, triggerMapper_1.buildAliyunHttpTriggerConfig)(fn.triggers.http) })) {
241
+ reasons.push('PLAN_DRIFT_HTTP_TRIGGER');
242
+ }
243
+ }
244
+ if (fn.domain) {
245
+ const domain = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getCustomDomain:${fn.domain.domain_name}`, () => client.fc3.getCustomDomain(fn.domain.domain_name));
246
+ if (!domain ||
247
+ (domain.protocol !== undefined && domain.protocol !== fn.domain.protocol) ||
248
+ (domain.certConfig?.certificateId !== undefined &&
249
+ fn.domain.certificate_id !== undefined &&
250
+ domain.certConfig.certificateId !== fn.domain.certificate_id)) {
251
+ reasons.push('PLAN_DRIFT_FUNCTION_DOMAIN');
252
+ }
253
+ }
254
+ return reasons;
255
+ };
208
256
  const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
209
257
  // Each declared dimension contributes its own probe; undeclared dimensions
210
258
  // fall through so later dimensions still run.
@@ -283,9 +331,8 @@ const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
283
331
  // against the desired timers (name-keyed). A trigger missing from the cloud
284
332
  // (manual delete), an edited cron/payload/enable, or an extra undeclared
285
333
  // timer all count as drift.
286
- const timerStateInstances = currentState.instances?.filter((i) => i.type === 'ALIYUN_FC3_TIMER_TRIGGER');
287
334
  const desiredTimers = fn.triggers?.timer ?? [];
288
- if (desiredTimers.length > 0 || timerStateInstances.length > 0) {
335
+ if (fn.triggers?.timer !== undefined) {
289
336
  const liveTriggerList = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.listTriggers:${fn.name}`, () => client.fc3.listTriggers(fn.name));
290
337
  const liveTimers = (liveTriggerList ?? []).filter((trigger) => trigger.triggerType === 'timer' && trigger.triggerName);
291
338
  const desiredNames = new Set(desiredTimers.map((timer) => timer.name));
@@ -298,6 +345,7 @@ const detectFunctionNestedDrift = async (context, client, fn, currentState) => {
298
345
  const liveConfig = (live.triggerConfig ?? {});
299
346
  return (liveConfig.cronExpression !== (0, siCron_1.translateSiCron)(timer.cron, 'aliyun') ||
300
347
  (liveConfig.payload ?? '') !== (timer.payload ?? '') ||
348
+ (live.description ?? undefined) !== timer.description ||
301
349
  (liveConfig.enable === true || liveConfig.enable === 'true') !== timer.enable);
302
350
  });
303
351
  if (extraTimer || desiredChanged) {
@@ -318,161 +366,82 @@ const generateFunctionPlan = async (context, state, functions) => {
318
366
  const functionItems = await (0, concurrency_1.mapWithConcurrency)(functions, concurrency_1.PLAN_READ_CONCURRENCY, async (fn) => {
319
367
  const logicalId = `functions.${fn.key}`;
320
368
  const currentState = (0, common_1.getResource)(state, logicalId);
321
- const rawConfig = (0, fc3Types_1.functionToFc3Config)(fn);
322
- const config = await resolveVpcConfigSecurityGroup(context, rawConfig);
369
+ const rawConfig = (0, fc3Types_2.functionToFc3Config)(fn);
370
+ const config = (0, fc3Types_1.resolveRecordedFc3NasConfig)(await resolveVpcConfigSecurityGroup(context, rawConfig), fn, currentState?.instances ?? []);
323
371
  const desiredCodeHash = fn.code ? await (0, common_1.computeZipContentHash)(fn.code.path) : null;
324
- const baseDefinition = (0, fc3Types_1.extractFc3Definition)(config, desiredCodeHash);
372
+ const baseDefinition = (0, fc3Types_2.extractFc3Definition)(config, desiredCodeHash, fn);
325
373
  const desiredDefinition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
326
- if (!currentState || currentState.status === 'tainted') {
327
- // No usable local state: probe the provider before planning create.
328
- // If a same-named function already exists WITHOUT our ownership tag it
329
- // may belong to another project — fail fast in the plan instead of
330
- // letting the executor discover it mid-deploy.
331
- const client = (0, aliyunClient_1.createAliyunClient)(context);
332
- const remoteFunction = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getFunction:${fn.name}`, () => client.fc3.getFunction(fn.name));
333
- if (remoteFunction && !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, remoteFunction.tags)) {
334
- throw new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED', {
335
- resourceType: 'Function',
336
- resourceName: fn.name,
337
- tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
338
- }));
339
- }
340
- return {
341
- logicalId,
342
- action: 'create',
343
- resourceType: 'ALIYUN_FC3',
344
- changes: { after: desiredDefinition },
345
- };
346
- }
347
- try {
348
- const client = (0, aliyunClient_1.createAliyunClient)(context);
349
- const normalizedCurrent = normalizeDefinitionForComparison(currentState.definition || {});
350
- const normalizedDesired = normalizeDefinitionForComparison(desiredDefinition);
351
- const definitionChanged = !(0, common_1.attributesEqual)(normalizedCurrent, normalizedDesired);
352
- // --no-refresh: no live read, no drift claims — intent-diff only.
353
- if (context.refresh === false) {
354
- if (!definitionChanged) {
355
- return { logicalId, action: 'noop', resourceType: 'ALIYUN_FC3' };
356
- }
357
- return {
358
- logicalId,
359
- action: 'update',
360
- resourceType: 'ALIYUN_FC3',
361
- changes: { before: normalizedCurrent, after: normalizedDesired },
374
+ const client = (0, aliyunClient_1.createAliyunClient)(context);
375
+ return (0, refreshPlanner_1.planRefreshedResource)({
376
+ logicalId,
377
+ resourceType: 'ALIYUN_FC3',
378
+ currentState,
379
+ desiredDefinition,
380
+ removedDependents: removedFc3Dependents(fn, currentState),
381
+ read: () => (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getFunction:${fn.name}`, () => client.fc3.getFunction(fn.name)),
382
+ isOwned: (remote) => (0, ownershipTag_1.isOwnedByStack)(context, logicalId, remote.tags),
383
+ foreignError: () => new Error(lang_1.lang.__('RESOURCE_EXISTS_NOT_OWNED', {
384
+ resourceType: 'Function',
385
+ resourceName: fn.name,
386
+ tagKey: ownershipTag_1.OWNERSHIP_TAG_KEY,
387
+ })),
388
+ cloudToDefinition: fc3Types_2.cloudFc3ToDefinition,
389
+ normalizeForDisplay: normalizeDefinitionForComparison,
390
+ extraUpdate: async () => {
391
+ if (!currentState)
392
+ return { update: false, drifted: false };
393
+ const roleProbe = resolveManagedRoleProbe(context, fn, currentState);
394
+ const roleReason = roleProbe
395
+ ? await (async () => {
396
+ const role = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.getRole:${roleProbe.roleName}`, () => client.ram.getRole(roleProbe.roleName));
397
+ return role
398
+ ? detectRolePolicyDrift(context, state, fn, currentState, roleProbe.roleName, role)
399
+ : 'PLAN_DRIFT_ROLE_MISSING';
400
+ })()
401
+ : null;
402
+ const lifecycleReasons = await detectFunctionLifecycleDrift(context, client, fn);
403
+ const nestedReason = await detectFunctionNestedDrift(context, client, fn, currentState);
404
+ const reasons = [roleReason, ...lifecycleReasons, nestedReason].filter((reason) => reason !== null);
405
+ const fields = {
406
+ PLAN_DRIFT_HTTP_TRIGGER: 'http',
407
+ PLAN_DRIFT_FUNCTION_DOMAIN: 'domain',
408
+ PLAN_DRIFT_TIMER_TRIGGER: 'timers',
362
409
  };
363
- }
364
- const remoteFunction = await (0, refreshCache_1.cachedRefreshRead)(context, `fc3.getFunction:${fn.name}`, () => client.fc3.getFunction(fn.name));
365
- if (!remoteFunction) {
366
410
  return {
367
- logicalId,
368
- action: 'create',
369
- resourceType: 'ALIYUN_FC3',
370
- changes: {
371
- before: normalizeDefinitionForComparison(currentState.definition),
372
- after: normalizeDefinitionForComparison(desiredDefinition),
373
- },
374
- drifted: true,
411
+ update: reasons.length > 0,
412
+ drifted: reasons.some((reason) => {
413
+ if (reason === 'PLAN_DRIFT_ROLE_POLICY') {
414
+ return !(0, planCompare_1.definitionsDiffer)(currentState.definition ?? {}, {
415
+ iam: desiredDefinition.iam,
416
+ vpcConfig: desiredDefinition.vpcConfig,
417
+ nasStorage: desiredDefinition.nasStorage,
418
+ logConfig: desiredDefinition.logConfig,
419
+ });
420
+ }
421
+ const field = fields[reason];
422
+ return (!field ||
423
+ !(0, planCompare_1.definitionsDiffer)(currentState.definition ?? {}, {
424
+ [field]: desiredDefinition[field],
425
+ }));
426
+ }),
427
+ reasons,
375
428
  };
376
- }
377
- // Issue #234 phase 1: live attribute drift. The stored definition can
378
- // be untouched while the console edited the deployed function
379
- // (memory/timeout/env/...). One-directional: only mapper-emitted keys
380
- // the desired definition declares are compared, so cloud-only extras
381
- // the config never asked for are ignored (desired-declared contract).
382
- // Issue #246: the diff baseline is cloud reality — live attributes
383
- // merged over the stored definition — and revertKeys marks the fields
384
- // whose difference is purely an out-of-config cloud edit.
385
- const remoteAttributes = (0, fc3Types_1.cloudFc3ToDefinition)(remoteFunction);
386
- const remoteDiffers = (0, planCompare_1.remoteDiffersFromDesired)(remoteAttributes, desiredDefinition);
387
- const liveBefore = normalizeDefinitionForComparison((0, planCompare_1.mergeLiveBefore)(currentState.definition || {}, remoteAttributes));
388
- const revertKeys = (0, planCompare_1.computeRevertKeys)(normalizedCurrent, normalizeDefinitionForComparison(remoteAttributes), normalizedDesired);
389
- if (definitionChanged || remoteDiffers) {
390
- return {
391
- logicalId,
392
- action: 'update',
393
- resourceType: 'ALIYUN_FC3',
394
- changes: { before: liveBefore, after: normalizedDesired },
395
- drifted: true,
396
- ...(revertKeys.length ? { revertKeys } : {}),
397
- };
398
- }
399
- const roleProbe = resolveManagedRoleProbe(context, fn, currentState);
400
- if (roleProbe) {
401
- try {
402
- const cloudRole = await (0, refreshCache_1.cachedRefreshRead)(context, `ram.getRole:${roleProbe.roleName}`, () => client.ram.getRole(roleProbe.roleName));
403
- if (!cloudRole) {
404
- common_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_ROLE_MISSING', {
405
- roleName: roleProbe.roleName,
406
- functionName: fn.name,
407
- }));
408
- return {
409
- logicalId,
410
- action: 'update',
411
- resourceType: 'ALIYUN_FC3',
412
- changes: { before: liveBefore, after: normalizedDesired },
413
- drifted: true,
414
- driftReasons: ['PLAN_DRIFT_ROLE_MISSING'],
415
- };
416
- }
417
- const roleDriftReason = await detectRolePolicyDrift(context, state, fn, currentState, roleProbe.roleName, cloudRole);
418
- if (roleDriftReason) {
419
- return {
420
- logicalId,
421
- action: 'update',
422
- resourceType: 'ALIYUN_FC3',
423
- changes: { before: liveBefore, after: normalizedDesired },
424
- drifted: true,
425
- driftReasons: [roleDriftReason],
426
- };
427
- }
428
- }
429
- catch (error) {
430
- common_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_ROLE_PROBE_FAILED', {
431
- roleName: roleProbe.roleName,
432
- functionName: fn.name,
433
- error: String(error),
434
- }));
435
- }
436
- }
437
- // Issue #234 M1/M2: nested drift probe — the probe itself skips
438
- // dimensions the config does not declare.
439
- try {
440
- const nestedDriftReason = await detectFunctionNestedDrift(context, client, fn, currentState);
441
- if (nestedDriftReason) {
442
- return {
443
- logicalId,
444
- action: 'update',
445
- resourceType: 'ALIYUN_FC3',
446
- changes: { before: liveBefore, after: normalizedDesired },
447
- drifted: true,
448
- driftReasons: [nestedDriftReason],
429
+ },
430
+ enrichRemoteAttributes: async (_remote, attributes) => {
431
+ // Lifecycle probes below verify these dimensions separately. Existing
432
+ // intent remains the baseline until those probes confirm equality.
433
+ const reason = currentState
434
+ ? await detectFunctionLifecycleDrift(context, client, fn)
435
+ : [];
436
+ return reason.length > 0
437
+ ? attributes
438
+ : {
439
+ ...attributes,
440
+ ...(fn.triggers?.http ? { http: fn.triggers.http } : {}),
449
441
  };
450
- }
451
- }
452
- catch (error) {
453
- common_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_NESTED_PROBE_FAILED', {
454
- functionName: fn.name,
455
- error: String(error),
456
- }));
457
- }
458
- return { logicalId, action: 'noop', resourceType: 'ALIYUN_FC3' };
459
- }
460
- catch (error) {
461
- common_1.logger.warn(lang_1.lang.__('PLAN_LIVE_READ_FAILED', {
462
- logicalId,
463
- error: error instanceof Error ? error.message : String(error),
464
- }));
465
- return {
466
- logicalId,
467
- action: 'create',
468
- resourceType: 'ALIYUN_FC3',
469
- changes: {
470
- before: normalizeDefinitionForComparison(currentState.definition),
471
- after: normalizeDefinitionForComparison(desiredDefinition),
472
- },
473
- drifted: true,
474
- };
475
- }
442
+ },
443
+ refresh: context.refresh,
444
+ });
476
445
  });
477
446
  const allStates = (0, common_1.getAllResources)(state);
478
447
  const deletionItems = Object.entries(allStates)
@@ -4,6 +4,10 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveFc3ExecutionStatements = exports.resolveRoleGrant = void 0;
7
+ const functionDefinition_1 = require("../../common/functionDefinition");
8
+ const planCompare_1 = require("../../common/planCompare");
9
+ const fc3Types_1 = require("./fc3Types");
10
+ const triggerMapper_1 = require("../../common/triggerMapper");
7
11
  const aliyunClient_1 = require("../../common/aliyunClient");
8
12
  const node_fs_1 = __importDefault(require("node:fs"));
9
13
  const node_path_1 = __importDefault(require("node:path"));
@@ -11,7 +15,7 @@ const common_1 = require("../../common");
11
15
  const constants_1 = require("../../common/constants");
12
16
  const types_1 = require("../../types");
13
17
  const siCron_1 = require("../../common/siCron");
14
- const fc3Types_1 = require("./fc3Types");
18
+ const fc3Types_2 = require("./fc3Types");
15
19
  const slsOperations_1 = require("../../common/aliyunClient/slsOperations");
16
20
  const ecsOperations_1 = require("../../common/aliyunClient/ecsOperations");
17
21
  const logger_1 = require("../../common/logger");
@@ -290,15 +294,7 @@ const buildFc3InstanceFromProvider = (info, sid) => {
290
294
  })),
291
295
  };
292
296
  };
293
- const buildHttpTriggerConfig = (trigger) => {
294
- const authType = (0, common_1.mapAuthType)(common_1.ProviderEnum.ALIYUN, trigger.auth_type);
295
- const { disableURLInternet } = (0, common_1.mapAliyunAccess)(trigger.access);
296
- return {
297
- authType,
298
- methods: ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'PATCH'],
299
- ...(disableURLInternet !== undefined ? { disableURLInternet } : {}),
300
- };
301
- };
297
+ const buildHttpTriggerConfig = triggerMapper_1.buildAliyunHttpTriggerConfig;
302
298
  const TIMER_TRIGGER_INSTANCE_TYPE = 'ALIYUN_FC3_TIMER_TRIGGER';
303
299
  /** FC3 timer dialect: 6-field cron (UTC+8), payload passthrough, enable flag. */
304
300
  const buildFc3TimerTriggerConfig = (timer) => ({
@@ -700,7 +696,7 @@ const createResource = async (context, fn, state) => {
700
696
  const stateWithSharedProject = dependentResources.sharedProject
701
697
  ? (0, common_1.setSharedResource)(state, context.stage, sharedLogProject_1.SHARED_LOG_PROJECT_KEY, dependentResources.sharedProject)
702
698
  : state;
703
- let config = (0, fc3Types_1.functionToFc3Config)(fn);
699
+ let config = (0, fc3Types_2.functionToFc3Config)(fn);
704
700
  config = {
705
701
  ...config,
706
702
  tags: [{ key: ownershipTag_1.OWNERSHIP_TAG_KEY, value: (0, ownershipTag_1.buildOwnershipTagValue)(context, logicalId) }],
@@ -735,21 +731,17 @@ const createResource = async (context, fn, state) => {
735
731
  if (dependentResources.nasConfig) {
736
732
  config = {
737
733
  ...config,
738
- nasConfig: {
739
- userId: -1,
740
- groupId: -1,
741
- mountPoints: dependentResources.nasConfig.mountPoints.map((mp) => ({
742
- serverAddr: mp.serverAddr,
743
- mountDir: mp.mountDir,
744
- })),
745
- },
734
+ nasConfig: (0, fc3Types_1.buildFc3NasConfig)(dependentResources.nasConfig.mountPoints.map((mp) => ({
735
+ serverAddr: mp.serverAddr,
736
+ mountDir: mp.mountDir,
737
+ }))),
746
738
  };
747
739
  }
748
740
  // Container-only functions have no code block — mirror the planner's null
749
741
  // codeHash (PR #237); the image lives in customContainerConfig, no zip push.
750
742
  const codePath = fn.code?.path;
751
743
  const codeHash = codePath ? await (0, common_1.computeZipContentHash)(codePath) : null;
752
- const baseDefinition = (0, fc3Types_1.extractFc3Definition)(config, codeHash);
744
+ const baseDefinition = (0, fc3Types_2.extractFc3Definition)(config, codeHash, fn);
753
745
  const definition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
754
746
  const dependentInstances = dependentResources.instances.map((dep) => ({
755
747
  sid: dep.sid ??
@@ -937,11 +929,12 @@ const withRecreatedMountTargets = (instances, recreated) => instances.map((insta
937
929
  const liveDomain = recreated[fileSystemId];
938
930
  return liveDomain ? { ...instance, id: `${fileSystemId}/${liveDomain}` } : instance;
939
931
  });
940
- const updateResource = async (context, fn, state, options) => {
932
+ const updateResource = async (context, providedFn, state, options) => {
941
933
  const ctx = (0, common_1.getContext)();
942
934
  const serviceName = `${ctx.app}-${ctx.service}`;
943
- const logicalId = `functions.${fn.key}`;
935
+ const logicalId = `functions.${providedFn.key}`;
944
936
  const existingState = (0, common_1.getResource)(state, logicalId);
937
+ const fn = (0, functionDefinition_1.withStoredFunctionIam)(providedFn, existingState?.definition);
945
938
  const existingInstances = (existingState?.instances ?? []);
946
939
  const hasSlsResources = existingInstances.some((i) => i.type === 'ALIYUN_SLS_PROJECT' ||
947
940
  i.type === 'ALIYUN_SLS_LOGSTORE' ||
@@ -975,7 +968,7 @@ const updateResource = async (context, fn, state, options) => {
975
968
  }
976
969
  else if (hasSlsResources) {
977
970
  const slsLogstoreInstance = existingInstances.find((i) => i.type === 'ALIYUN_SLS_LOGSTORE');
978
- if (fn.log) {
971
+ if (fn.log !== false) {
979
972
  if (slsLogstoreInstance) {
980
973
  const [projectName, logstoreName] = slsLogstoreInstance.id.split('/');
981
974
  logConfig = { project: projectName, logstore: logstoreName };
@@ -1004,6 +997,7 @@ const updateResource = async (context, fn, state, options) => {
1004
997
  }
1005
998
  catch (error) {
1006
999
  logger_1.logger.warn(lang_1.lang.__('NESTED_REPAIR_FAILED', { resource: logstoreName, error: String(error) }));
1000
+ throw error;
1007
1001
  }
1008
1002
  }
1009
1003
  }
@@ -1075,7 +1069,7 @@ const updateResource = async (context, fn, state, options) => {
1075
1069
  const existingIam = existingState?.definition?.iam;
1076
1070
  const desiredIam = fn.iam;
1077
1071
  const iamChanged = !(0, common_1.attributesEqual)(existingIam ?? {}, desiredIam ?? {});
1078
- if (iamChanged) {
1072
+ if (iamChanged || options?.force) {
1079
1073
  // Check for statement changes
1080
1074
  const desiredStatements = newIamRole ? newIamRole.statements : undefined;
1081
1075
  const existingRole = existingIam?.role;
@@ -1092,7 +1086,9 @@ const updateResource = async (context, fn, state, options) => {
1092
1086
  : undefined;
1093
1087
  const desiredManagedPoliciesVal = (desiredManagedPolicies ?? []);
1094
1088
  const existingManagedPoliciesVal = (existingManagedPolicies ?? []);
1095
- if (!(0, common_1.attributesEqual)(existingManagedPoliciesVal, desiredManagedPoliciesVal)) {
1089
+ if (desiredManagedPolicies !== undefined &&
1090
+ (options?.force ||
1091
+ !(0, common_1.attributesEqual)(existingManagedPoliciesVal, desiredManagedPoliciesVal))) {
1096
1092
  await client.ram.updateManagedPolicies(ramRoleInstance.id, desiredManagedPolicies ?? []);
1097
1093
  }
1098
1094
  }
@@ -1170,6 +1166,7 @@ const updateResource = async (context, fn, state, options) => {
1170
1166
  }
1171
1167
  catch (error) {
1172
1168
  logger_1.logger.warn(lang_1.lang.__('NESTED_REPAIR_FAILED', { resource: sgInstance.id, error: String(error) }));
1169
+ throw error;
1173
1170
  }
1174
1171
  }
1175
1172
  }
@@ -1216,6 +1213,7 @@ const updateResource = async (context, fn, state, options) => {
1216
1213
  }
1217
1214
  catch (error) {
1218
1215
  logger_1.logger.warn(lang_1.lang.__('NESTED_REPAIR_FAILED', { resource: failingFsId ?? 'nas', error: String(error) }));
1216
+ throw error;
1219
1217
  }
1220
1218
  }
1221
1219
  if (mountTargetInstances.length > 0 && nasStorageItems.length > 0) {
@@ -1233,7 +1231,7 @@ const updateResource = async (context, fn, state, options) => {
1233
1231
  };
1234
1232
  }
1235
1233
  }
1236
- let config = (0, fc3Types_1.functionToFc3Config)(fn);
1234
+ let config = (0, fc3Types_2.functionToFc3Config)(fn);
1237
1235
  if (logConfig) {
1238
1236
  config = {
1239
1237
  ...config,
@@ -1264,11 +1262,7 @@ const updateResource = async (context, fn, state, options) => {
1264
1262
  if (nasConfig) {
1265
1263
  config = {
1266
1264
  ...config,
1267
- nasConfig: {
1268
- userId: -1,
1269
- groupId: -1,
1270
- mountPoints: nasConfig.mountPoints,
1271
- },
1265
+ nasConfig: (0, fc3Types_1.buildFc3NasConfig)(nasConfig.mountPoints),
1272
1266
  };
1273
1267
  }
1274
1268
  const codePath = fn.code?.path;
@@ -1276,10 +1270,10 @@ const updateResource = async (context, fn, state, options) => {
1276
1270
  const desiredCodeHash = codePath ? await (0, common_1.computeZipContentHash)(codePath) : null;
1277
1271
  const codeChanged = codePath ? currentCodeHash !== desiredCodeHash : false;
1278
1272
  const existingConfig = existingState?.definition;
1279
- const desiredDefinition = (0, fc3Types_1.extractFc3Definition)(config, desiredCodeHash);
1280
- const { codeHash: _existingCodeHash, iam: _existingIam, ...existingConfigOnly } = existingConfig || {};
1281
- const { codeHash: _desiredCodeHash, ...desiredConfigOnly } = desiredDefinition;
1282
- const configChanged = !(0, common_1.attributesEqual)(existingConfigOnly, desiredConfigOnly);
1273
+ const desiredDefinition = (0, fc3Types_2.extractFc3Definition)(config, desiredCodeHash, fn);
1274
+ const { codeHash: _existingCodeHash, iam: _existingIam, http: _existingHttp, domain: _existingDomain, timers: _existingTimers, ...existingConfigOnly } = existingConfig || {};
1275
+ const { codeHash: _desiredCodeHash, http: _desiredHttp, domain: _desiredDomain, timers: _desiredTimers, ...desiredConfigOnly } = desiredDefinition;
1276
+ const configChanged = (0, planCompare_1.definitionsDiffer)(existingConfigOnly, desiredConfigOnly);
1283
1277
  // `force` carries the plan's drifted flag: a live-drift update (state
1284
1278
  // matches config, cloud edited in console) must re-push the config even
1285
1279
  // though state-vs-desired sees no change.
@@ -1331,23 +1325,10 @@ const updateResource = async (context, fn, state, options) => {
1331
1325
  await client.fc3.createTrigger(fn.name, 'http-trigger', 'http', triggerConfig);
1332
1326
  logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName: 'http-trigger', functionName: fn.name }));
1333
1327
  }
1334
- else if (!desiredHttpTrigger && existingHttpTrigger) {
1335
- logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName: 'http-trigger', functionName: fn.name }));
1336
- try {
1337
- await client.fc3.deleteTrigger(fn.name, 'http-trigger');
1338
- logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName: 'http-trigger' }));
1339
- }
1340
- catch (err) {
1341
- const errorCode = err?.code;
1342
- if (errorCode !== 'TriggerNotFound')
1343
- throw err;
1344
- logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', { triggerName: 'http-trigger' }));
1345
- }
1346
- }
1347
1328
  else if (desiredHttpTrigger && existingHttpTrigger) {
1348
1329
  const desiredTriggerConfig = buildHttpTriggerConfig(desiredHttpTrigger);
1349
1330
  const existingAttrs = existingHttpTrigger.attributes ?? {};
1350
- if (!(0, common_1.attributesEqual)(desiredTriggerConfig, existingAttrs)) {
1331
+ if (options?.repairHttp || !(0, common_1.attributesEqual)(desiredTriggerConfig, existingAttrs)) {
1351
1332
  logger_1.logger.info(lang_1.lang.__('UPDATING_HTTP_TRIGGER', { functionName: fn.name }));
1352
1333
  try {
1353
1334
  await client.fc3.deleteTrigger(fn.name, 'http-trigger');
@@ -1361,6 +1342,19 @@ const updateResource = async (context, fn, state, options) => {
1361
1342
  logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_CREATED', { triggerName: 'http-trigger', functionName: fn.name }));
1362
1343
  }
1363
1344
  }
1345
+ else if (!desiredHttpTrigger && existingHttpTrigger) {
1346
+ logger_1.logger.info(lang_1.lang.__('DELETING_HTTP_TRIGGER', { triggerName: 'http-trigger', functionName: fn.name }));
1347
+ try {
1348
+ await client.fc3.deleteTrigger(fn.name, 'http-trigger');
1349
+ logger_1.logger.info(lang_1.lang.__('HTTP_TRIGGER_DELETED', { triggerName: 'http-trigger' }));
1350
+ }
1351
+ catch (err) {
1352
+ const errorCode = err?.code;
1353
+ if (errorCode !== 'TriggerNotFound')
1354
+ throw err;
1355
+ logger_1.logger.warn(lang_1.lang.__('HTTP_TRIGGER_NOT_FOUND', { triggerName: 'http-trigger' }));
1356
+ }
1357
+ }
1364
1358
  const existingCustomDomain = existingInstances.find((i) => i.type === 'ALIYUN_FC3_CUSTOM_DOMAIN');
1365
1359
  const desiredDomain = fn.domain;
1366
1360
  const timerInstances = await reconcileFc3TimerTriggers(context, fn, existingInstances, client);
@@ -1400,7 +1394,9 @@ const updateResource = async (context, fn, state, options) => {
1400
1394
  }
1401
1395
  else if (desiredDomain && existingCustomDomain) {
1402
1396
  const existingProtocol = existingCustomDomain.attributes?.protocol;
1403
- const domainChanged = desiredDomain.domain_name !== existingCustomDomain.id ||
1397
+ const domainChanged = options?.repairDomain ||
1398
+ !(0, common_1.attributesEqual)(existingState?.definition?.domain ?? {}, desiredDomain) ||
1399
+ desiredDomain.domain_name !== existingCustomDomain.id ||
1404
1400
  desiredDomain.protocol !== existingProtocol;
1405
1401
  if (domainChanged) {
1406
1402
  logger_1.logger.info(lang_1.lang.__('UPDATING_CUSTOM_DOMAIN', { domainName: desiredDomain.domain_name }));
@@ -1434,7 +1430,7 @@ const updateResource = async (context, fn, state, options) => {
1434
1430
  throw new Error(lang_1.lang.__('REFRESH_STATE_FUNCTION', { name: fn.name }));
1435
1431
  }
1436
1432
  const codeHash = codePath ? await (0, common_1.computeZipContentHash)(codePath) : null;
1437
- const baseDefinition = (0, fc3Types_1.extractFc3Definition)(config, codeHash);
1433
+ const baseDefinition = (0, fc3Types_2.extractFc3Definition)(config, codeHash, fn);
1438
1434
  const definition = fn.iam ? { ...baseDefinition, iam: fn.iam } : baseDefinition;
1439
1435
  const sid = (0, common_1.buildSid)('aliyun', 'fc3', context.stage, fn.name);
1440
1436
  const fcInstance = buildFc3InstanceFromProvider(functionInfo, sid);
@@ -1486,7 +1482,7 @@ const updateResource = async (context, fn, state, options) => {
1486
1482
  const resourceState = {
1487
1483
  mode: 'managed',
1488
1484
  region: context.region,
1489
- definition,
1485
+ definition: (0, functionDefinition_1.withLifecycleIntent)((0, planCompare_1.mergeManagedIntent)(existingState?.definition ?? {}, definition), definition, ['http', 'domain', 'timers']),
1490
1486
  instances: [
1491
1487
  fcInstance,
1492
1488
  ...lifecycleInstances,