@geek-fun/serverlessinsight 0.8.7 → 0.8.9

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 (65) 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 +94 -0
  4. package/.serverlessinsight/state-insight-poc-deploy-app-insight-poc-deploy.json.backup +36 -16
  5. package/.serverlessinsight/state-insight-poc-destroy-app-insight-poc-destroy.json.backup +1 -1
  6. package/.serverlessinsight/state-insight-volc-app-insight-volc.json.backup +35 -73
  7. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +148 -0
  8. package/dist/package.json +1 -1
  9. package/dist/src/commands/deploy.js +1 -0
  10. package/dist/src/commands/index.js +6 -2
  11. package/dist/src/commands/plan.js +1 -0
  12. package/dist/src/common/aliyunClient/ecsOperations.js +70 -1
  13. package/dist/src/common/aliyunClient/index.js +44 -35
  14. package/dist/src/common/aliyunClient/nasOperations.js +21 -0
  15. package/dist/src/common/aliyunClient/ramOperations.js +32 -20
  16. package/dist/src/common/aliyunClient/slsOperations.js +16 -3
  17. package/dist/src/common/concurrency.js +30 -0
  18. package/dist/src/common/constants.js +5 -1
  19. package/dist/src/common/context.js +3 -0
  20. package/dist/src/common/dependencyGraph/graph.js +5 -0
  21. package/dist/src/common/imsClient.js +2 -2
  22. package/dist/src/common/index.js +5 -0
  23. package/dist/src/common/planCompare.js +62 -0
  24. package/dist/src/common/planFormatter.js +15 -3
  25. package/dist/src/common/refreshCache.js +32 -0
  26. package/dist/src/common/refreshPlanner.js +105 -0
  27. package/dist/src/common/tencentClient/clsOperations.js +27 -3
  28. package/dist/src/common/tencentClient/tdsqlcOperations.js +22 -0
  29. package/dist/src/common/throttleRetry.js +56 -0
  30. package/dist/src/common/volcengineClient/tlsOperations.js +12 -4
  31. package/dist/src/lang/en.js +16 -0
  32. package/dist/src/lang/zh-CN.js +16 -0
  33. package/dist/src/stack/aliyunStack/apigwPlanner.js +75 -7
  34. package/dist/src/stack/aliyunStack/apigwTypes.js +67 -1
  35. package/dist/src/stack/aliyunStack/databasePlanner.js +26 -62
  36. package/dist/src/stack/aliyunStack/esServerlessTypes.js +50 -1
  37. package/dist/src/stack/aliyunStack/fc3Executor.js +5 -3
  38. package/dist/src/stack/aliyunStack/fc3Planner.js +299 -12
  39. package/dist/src/stack/aliyunStack/fc3Resource.js +221 -30
  40. package/dist/src/stack/aliyunStack/fc3Types.js +61 -1
  41. package/dist/src/stack/aliyunStack/ossPlanner.js +21 -63
  42. package/dist/src/stack/aliyunStack/ossTypes.js +25 -1
  43. package/dist/src/stack/aliyunStack/rdsTypes.js +38 -1
  44. package/dist/src/stack/aliyunStack/tablestorePlanner.js +20 -74
  45. package/dist/src/stack/aliyunStack/tablestoreTypes.js +33 -1
  46. package/dist/src/stack/scfStack/cosPlanner.js +30 -50
  47. package/dist/src/stack/scfStack/cosTypes.js +29 -1
  48. package/dist/src/stack/scfStack/esServerlessPlanner.js +21 -54
  49. package/dist/src/stack/scfStack/esServerlessTypes.js +13 -1
  50. package/dist/src/stack/scfStack/scfExecutor.js +5 -3
  51. package/dist/src/stack/scfStack/scfPlanner.js +71 -50
  52. package/dist/src/stack/scfStack/scfResource.js +37 -2
  53. package/dist/src/stack/scfStack/scfTypes.js +35 -1
  54. package/dist/src/stack/scfStack/sharedLogset.js +3 -2
  55. package/dist/src/stack/scfStack/tdsqlcPlanner.js +37 -55
  56. package/dist/src/stack/scfStack/tdsqlcTypes.js +21 -1
  57. package/dist/src/stack/volcengineStack/apigwPlanner.js +54 -7
  58. package/dist/src/stack/volcengineStack/apigwTypes.js +26 -1
  59. package/dist/src/stack/volcengineStack/tosPlanner.js +28 -55
  60. package/dist/src/stack/volcengineStack/tosTypes.js +18 -1
  61. package/dist/src/stack/volcengineStack/vefaasExecutor.js +5 -3
  62. package/dist/src/stack/volcengineStack/vefaasPlanner.js +114 -6
  63. package/dist/src/stack/volcengineStack/vefaasResource.js +40 -5
  64. package/dist/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +1 -1
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveFc3ExecutionStatements = void 0;
6
+ exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveFc3ExecutionStatements = exports.resolveRoleGrant = void 0;
7
7
  const aliyunClient_1 = require("../../common/aliyunClient");
8
8
  const node_fs_1 = __importDefault(require("node:fs"));
9
9
  const node_path_1 = __importDefault(require("node:path"));
@@ -11,6 +11,8 @@ const common_1 = require("../../common");
11
11
  const constants_1 = require("../../common/constants");
12
12
  const types_1 = require("../../types");
13
13
  const fc3Types_1 = require("./fc3Types");
14
+ const slsOperations_1 = require("../../common/aliyunClient/slsOperations");
15
+ const ecsOperations_1 = require("../../common/aliyunClient/ecsOperations");
14
16
  const logger_1 = require("../../common/logger");
15
17
  const iamStatements_1 = require("../../common/iamStatements");
16
18
  const ramOperations_1 = require("../../common/aliyunClient/ramOperations");
@@ -115,6 +117,7 @@ const resolveRoleGrant = (context, state, fn, logConfig, roleId) => {
115
117
  customStatements,
116
118
  };
117
119
  };
120
+ exports.resolveRoleGrant = resolveRoleGrant;
118
121
  const buildFcFunctionArn = (context, functionName) => context.accountId
119
122
  ? `acs:fc:${context.region}:${context.accountId}:functions/${functionName}`
120
123
  : undefined;
@@ -291,7 +294,7 @@ const buildHttpTriggerConfig = (trigger) => {
291
294
  ...(disableURLInternet !== undefined ? { disableURLInternet } : {}),
292
295
  };
293
296
  };
294
- const createDependentResources = async (context, fn, serviceName, existingInstances = [], state, executionStatementsOverride) => {
297
+ const createDependentResources = async (context, fn, serviceName, existingInstances = [], state, options) => {
295
298
  const client = (0, aliyunClient_1.createAliyunClient)(context);
296
299
  const instances = [];
297
300
  let logConfig;
@@ -302,6 +305,10 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
302
305
  const hasRamRole = existingInstances.some((i) => i.type === 'ALIYUN_RAM_ROLE');
303
306
  const hasSecurityGroup = existingInstances.some((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
304
307
  const hasNasResources = existingInstances.some((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
308
+ // Callers that reconcile the role themselves (updateResource) opt out so the
309
+ // helper neither re-creates a just-repaired role nor rewrites the execution
310
+ // policy from a grant derived without the caller's logConfig.
311
+ const skipRole = options?.skipRole === true;
305
312
  if (fn.log) {
306
313
  if (hasSlsProject) {
307
314
  const slsProjectInstance = existingInstances.find((i) => i.type === 'ALIYUN_SLS_PROJECT');
@@ -330,14 +337,11 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
330
337
  }
331
338
  }
332
339
  const iamConfig = fn.iam?.role;
333
- const statements = iamConfig && typeof iamConfig !== 'string' ? iamConfig.statements : undefined;
334
340
  const managedPolicies = iamConfig && typeof iamConfig !== 'string' ? iamConfig.managed_policies : undefined;
335
341
  const customRoleName = iamConfig && typeof iamConfig !== 'string' ? iamConfig.name : undefined;
336
342
  const defaultRoleName = buildDefaultRoleName(serviceName, context.stage, fn.key);
337
- const trustedServices = getTrustedServicesForFunction(context, fn);
338
- const executionStatements = executionStatementsOverride ?? (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig);
339
343
  const isExternalRole = typeof iamConfig === 'string';
340
- if (isExternalRole) {
344
+ if (isExternalRole && !skipRole) {
341
345
  // External role - use ARN directly, skip creation and management
342
346
  instances.push({
343
347
  type: 'ALIYUN_RAM_ROLE',
@@ -347,22 +351,40 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
347
351
  attributes: {},
348
352
  });
349
353
  }
350
- else if (hasRamRole) {
354
+ else if (!skipRole && hasRamRole) {
351
355
  const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
352
356
  if (ramRoleInstance) {
353
- instances.push(ramRoleInstance);
354
- const roleGrant = resolveRoleGrant(context, state, fn, logConfig, ramRoleInstance.id);
355
- await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
356
- await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
357
- if (managedPolicies?.length) {
358
- await client.ram.attachManagedPolicies(ramRoleInstance.id, managedPolicies);
357
+ const cloudRole = await client.ram.getRole(ramRoleInstance.id);
358
+ if (!cloudRole) {
359
+ // Issue #234: recorded instance but provider role gone — rebuild with
360
+ // peer-union grants instead of failing on the trust-policy update.
361
+ logger_1.logger.warn(lang_1.lang.__('RAM_ROLE_MISSING_RECREATE', { roleName: ramRoleInstance.id }));
362
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, ramRoleInstance.id);
363
+ const ramRole = await client.ram.createRole(ramRoleInstance.id, roleGrant.trustedServices, undefined, roleGrant.customStatements, managedPolicies, roleGrant.executionStatements);
364
+ instances.push({
365
+ type: 'ALIYUN_RAM_ROLE',
366
+ id: ramRoleInstance.id,
367
+ roleArn: ramRole.arn,
368
+ attributes: { ...ramRole },
369
+ });
370
+ await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
371
+ }
372
+ else {
373
+ instances.push(ramRoleInstance);
374
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, ramRoleInstance.id);
375
+ await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
376
+ await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
377
+ if (managedPolicies?.length) {
378
+ await client.ram.attachManagedPolicies(ramRoleInstance.id, managedPolicies);
379
+ }
359
380
  }
360
381
  }
361
382
  }
362
- else {
383
+ else if (!skipRole) {
363
384
  const roleName = customRoleName ?? defaultRoleName;
385
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, roleName);
364
386
  logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
365
- const ramRole = await client.ram.createRole(roleName, trustedServices, undefined, statements, managedPolicies, executionStatements);
387
+ const ramRole = await client.ram.createRole(roleName, roleGrant.trustedServices, undefined, roleGrant.customStatements, managedPolicies, roleGrant.executionStatements);
366
388
  instances.push({
367
389
  type: 'ALIYUN_RAM_ROLE',
368
390
  id: roleName,
@@ -372,13 +394,17 @@ const createDependentResources = async (context, fn, serviceName, existingInstan
372
394
  await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
373
395
  }
374
396
  const ramRoleInstance = instances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
375
- const role = isExternalRole
376
- ? { roleName: '', arn: iamConfig }
377
- : {
397
+ let role;
398
+ if (isExternalRole) {
399
+ role = { roleName: '', arn: iamConfig };
400
+ }
401
+ else if (!skipRole) {
402
+ role = {
378
403
  roleName: customRoleName ?? defaultRoleName,
379
404
  arn: ramRoleInstance?.roleArn ??
380
405
  `acs:ram::${context.accountId}:role/${customRoleName ?? defaultRoleName}`,
381
406
  };
407
+ }
382
408
  if (fn.network) {
383
409
  if (hasSecurityGroup) {
384
410
  const sgInstance = existingInstances.find((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
@@ -735,7 +761,7 @@ const readResource = async (context, functionName) => {
735
761
  return await client.fc3.getFunction(functionName);
736
762
  };
737
763
  exports.readResource = readResource;
738
- const updateResource = async (context, fn, state) => {
764
+ const updateResource = async (context, fn, state, options) => {
739
765
  const ctx = (0, common_1.getContext)();
740
766
  const serviceName = `${ctx.app}-${ctx.service}`;
741
767
  const logicalId = `functions.${fn.key}`;
@@ -744,7 +770,6 @@ const updateResource = async (context, fn, state) => {
744
770
  const hasSlsResources = existingInstances.some((i) => i.type === 'ALIYUN_SLS_PROJECT' ||
745
771
  i.type === 'ALIYUN_SLS_LOGSTORE' ||
746
772
  i.type === 'ALIYUN_SLS_INDEX');
747
- const hasRamRole = existingInstances.some((i) => i.type === 'ALIYUN_RAM_ROLE');
748
773
  const hasSecurityGroup = existingInstances.some((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
749
774
  const hasNasResources = existingInstances.some((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
750
775
  const client = (0, aliyunClient_1.createAliyunClient)(context);
@@ -761,7 +786,7 @@ const updateResource = async (context, fn, state) => {
761
786
  // shared-state entry is removed from the returned state.
762
787
  let releasedSharedProject = false;
763
788
  if (fn.log && !hasSlsResources) {
764
- const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state);
789
+ const deps = await createDependentResources(context, { ...fn, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, { skipRole: true });
765
790
  logConfig = deps.logConfig;
766
791
  newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('ALIYUN_SLS_')));
767
792
  if (deps.sharedProject) {
@@ -774,6 +799,33 @@ const updateResource = async (context, fn, state) => {
774
799
  if (slsLogstoreInstance) {
775
800
  const [projectName, logstoreName] = slsLogstoreInstance.id.split('/');
776
801
  logConfig = { project: projectName, logstore: logstoreName };
802
+ // Issue #234 M1: nested repair — only on a drifted plan item (force):
803
+ // reconcile logstore ttl/shards and index presence against what si
804
+ // creates. Shard deficits are repaired upward; Aliyun cannot shrink.
805
+ if (options?.force) {
806
+ // Nested repair is best-effort: a transient read/write failure here
807
+ // must not fail the function update itself (SLS ReadTimeout in prod).
808
+ try {
809
+ const liveLogstore = await client.sls.getLogstore(projectName, logstoreName);
810
+ if (!liveLogstore) {
811
+ logger_1.logger.warn(lang_1.lang.__('NESTED_LOGSTORE_RECREATED', { logstoreName }));
812
+ await client.sls.createLogstore(projectName, logstoreName);
813
+ }
814
+ else if (liveLogstore.ttl !== slsOperations_1.SLS_LOGSTORE_TTL ||
815
+ (liveLogstore.shardCount ?? 0) < slsOperations_1.SLS_LOGSTORE_SHARDS) {
816
+ await client.sls.updateLogstore(projectName, logstoreName, slsOperations_1.SLS_LOGSTORE_TTL, Math.max(liveLogstore.shardCount ?? 0, slsOperations_1.SLS_LOGSTORE_SHARDS));
817
+ logger_1.logger.info(lang_1.lang.__('NESTED_LOGSTORE_UPDATED', { logstoreName }));
818
+ }
819
+ const liveIndex = await client.sls.getIndex(projectName, logstoreName);
820
+ if (!liveIndex) {
821
+ logger_1.logger.warn(lang_1.lang.__('NESTED_INDEX_RECREATED', { logstoreName }));
822
+ await client.sls.createIndex(projectName, logstoreName);
823
+ }
824
+ }
825
+ catch (error) {
826
+ logger_1.logger.warn(lang_1.lang.__('NESTED_REPAIR_FAILED', { resource: logstoreName, error: String(error) }));
827
+ }
828
+ }
777
829
  }
778
830
  }
779
831
  else {
@@ -786,23 +838,58 @@ const updateResource = async (context, fn, state) => {
786
838
  }
787
839
  const newIamRole = fn.iam?.role;
788
840
  const executionStatements = (0, exports.deriveFc3ExecutionStatements)(fn, context, logConfig);
841
+ const iamRoleConfig = newIamRole && typeof newIamRole !== 'string' ? newIamRole : undefined;
842
+ const customRoleName = iamRoleConfig?.name;
843
+ const desiredManagedPolicies = iamRoleConfig?.managed_policies;
844
+ // A role created/recreated in this run must rebind the function even when the
845
+ // compared definition is unchanged — role is not part of extractFc3Definition.
846
+ let roleBindingChanged = false;
847
+ const droppedRamRoleIds = new Set();
848
+ const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
849
+ // Issue #234 dual check: a recorded instance is not trusted on its own — when
850
+ // the provider role is gone, the create path below rebuilds it with
851
+ // peer-union grants and drops the stale instance from the resulting state.
852
+ // External roles are recorded with the ARN as the instance id, which is not a
853
+ // valid GetRole roleName input, and the external branch below never consults
854
+ // the probe — so only recorded managed roles are probed.
855
+ const isRecordedRoleExternal = Boolean(ramRoleInstance?.external);
856
+ const cloudRoleExists = ramRoleInstance && !isRecordedRoleExternal && typeof newIamRole !== 'string'
857
+ ? Boolean(await client.ram.getRole(ramRoleInstance.id))
858
+ : false;
789
859
  if (typeof newIamRole === 'string') {
790
860
  // External role - use ARN directly, skip management
791
861
  role = { roleName: '', arn: newIamRole };
792
862
  }
793
- else if (!hasRamRole) {
794
- const deps = await createDependentResources(context, { ...fn, log: false, network: undefined, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, executionStatements);
795
- role = deps.role;
796
- newDependentInstances.push(...deps.instances.filter((i) => i.type === 'ALIYUN_RAM_ROLE'));
863
+ else if (!ramRoleInstance || isRecordedRoleExternal || !cloudRoleExists) {
864
+ const roleName = (isRecordedRoleExternal ? undefined : ramRoleInstance?.id) ??
865
+ customRoleName ??
866
+ buildDefaultRoleName(serviceName, context.stage, fn.key);
867
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, roleName);
868
+ logger_1.logger.info(lang_1.lang.__('CREATING_RAM_ROLE', { roleName }));
869
+ const ramRole = await client.ram.createRole(roleName, roleGrant.trustedServices, undefined, roleGrant.customStatements, desiredManagedPolicies, roleGrant.executionStatements);
870
+ role = {
871
+ roleName,
872
+ arn: ramRole.arn ?? `acs:ram::${context.accountId}:role/${roleName}`,
873
+ };
874
+ if (ramRoleInstance) {
875
+ droppedRamRoleIds.add(ramRoleInstance.id);
876
+ }
877
+ newDependentInstances.push({
878
+ type: 'ALIYUN_RAM_ROLE',
879
+ id: roleName,
880
+ roleArn: role.arn,
881
+ attributes: { ...ramRole },
882
+ });
883
+ await delay(constants_1.RAM_ROLE_PROPAGATION_DELAY_MS);
884
+ roleBindingChanged = true;
797
885
  }
798
886
  else {
799
- const ramRoleInstance = existingInstances.find((i) => i.type === 'ALIYUN_RAM_ROLE');
800
887
  if (ramRoleInstance) {
801
888
  role = {
802
889
  roleName: ramRoleInstance.id,
803
890
  arn: ramRoleInstance.roleArn ?? `acs:ram::${context.accountId}:role/${ramRoleInstance.id}`,
804
891
  };
805
- const roleGrant = resolveRoleGrant(context, state, fn, logConfig, ramRoleInstance.id);
892
+ const roleGrant = (0, exports.resolveRoleGrant)(context, state, fn, logConfig, ramRoleInstance.id);
806
893
  await client.ram.updateRoleTrustPolicy(ramRoleInstance.id, roleGrant.trustedServices);
807
894
  await client.ram.updateExecutionPolicyDocument(ramRoleInstance.id, (0, ramOperations_1.buildFc3ExecutionPolicyDocument)(roleGrant.executionStatements, roleGrant.customStatements));
808
895
  const existingIam = existingState?.definition?.iam;
@@ -832,7 +919,7 @@ const updateResource = async (context, fn, state) => {
832
919
  }
833
920
  }
834
921
  if (fn.network && !hasSecurityGroup) {
835
- const deps = await createDependentResources(context, { ...fn, log: false, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, executionStatements);
922
+ const deps = await createDependentResources(context, { ...fn, log: false, storage: { ...fn.storage, nas: undefined } }, serviceName, undefined, state, { skipRole: true });
836
923
  securityGroup = deps.securityGroup;
837
924
  newDependentInstances.push(...deps.instances.filter((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP'));
838
925
  }
@@ -840,16 +927,116 @@ const updateResource = async (context, fn, state) => {
840
927
  const sgInstance = existingInstances.find((i) => i.type === 'ALIYUN_ECS_SECURITY_GROUP');
841
928
  if (sgInstance) {
842
929
  securityGroup = { securityGroupId: sgInstance.id };
930
+ // Issue #234 M2: SG rule reconcile — only on a drifted plan item
931
+ // (force): authorize rules missing from the live set, revoke rules the
932
+ // config no longer declares. Invalid config rules are skipped at create
933
+ // time too.
934
+ if (options?.force && fn.network) {
935
+ // Best-effort: a transient SG read failure must not fail the update.
936
+ try {
937
+ const parseRule = (rule) => {
938
+ try {
939
+ return (0, ecsOperations_1.parseSecurityGroupRule)(rule);
940
+ }
941
+ catch {
942
+ return null;
943
+ }
944
+ };
945
+ const desiredIngress = (fn.network.security_group.ingress ?? [])
946
+ .map(parseRule)
947
+ .filter((r) => Boolean(r));
948
+ const desiredEgress = (fn.network.security_group.egress ?? [])
949
+ .map(parseRule)
950
+ .filter((r) => Boolean(r));
951
+ const live = await client.ecs.getSecurityGroupRules(sgInstance.id);
952
+ const liveIngressKeys = (live?.ingressRules ?? []).map((r) => (0, ecsOperations_1.canonicalSecurityGroupRule)(r.ipProtocol ?? '', r.portRange ?? '', r.sourceCidrIp ?? ''));
953
+ const liveEgressKeys = (live?.egressRules ?? []).map((r) => (0, ecsOperations_1.canonicalSecurityGroupRule)(r.ipProtocol ?? '', r.portRange ?? '', r.destCidrIp ?? ''));
954
+ const missingIngress = desiredIngress.filter((d) => !liveIngressKeys.includes((0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr)));
955
+ const missingEgress = desiredEgress.filter((d) => !liveEgressKeys.includes((0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr)));
956
+ // The extra check reuses the raw live canonical keys — the same space
957
+ // the missing check uses. Reconstructing a parsed rule here would
958
+ // collapse port ranges (80/443 -> 80) and wrongly revoke matching
959
+ // range rules.
960
+ const desiredIngressKeys = desiredIngress.map((d) => (0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr));
961
+ const desiredEgressKeys = desiredEgress.map((d) => (0, ecsOperations_1.canonicalSecurityGroupRule)(d.protocol, d.portRange, d.cidr));
962
+ const extraIngress = (live?.ingressRules ?? []).filter((r, i) => {
963
+ const key = liveIngressKeys[i];
964
+ return !key || !desiredIngressKeys.includes(key);
965
+ });
966
+ const extraEgress = (live?.egressRules ?? []).filter((r, i) => {
967
+ const key = liveEgressKeys[i];
968
+ return !key || !desiredEgressKeys.includes(key);
969
+ });
970
+ if (missingIngress.length > 0 || missingEgress.length > 0) {
971
+ await client.ecs.authorizeSecurityGroupRules(sgInstance.id, 'ingress', missingIngress);
972
+ await client.ecs.authorizeSecurityGroupRules(sgInstance.id, 'egress', missingEgress);
973
+ }
974
+ if (extraIngress.length > 0 || extraEgress.length > 0) {
975
+ const toParsed = (r) => ({
976
+ // Live portRange is already in Aliyun wire format — pass verbatim
977
+ // so the revoke matches the rule exactly (ranges included).
978
+ protocol: r.ipProtocol ?? '',
979
+ cidr: r.sourceCidrIp ?? r.destCidrIp ?? '',
980
+ portRange: r.portRange ?? '',
981
+ });
982
+ await client.ecs.revokeSecurityGroupRules(sgInstance.id, 'ingress', extraIngress.map(toParsed));
983
+ await client.ecs.revokeSecurityGroupRules(sgInstance.id, 'egress', extraEgress.map(toParsed));
984
+ }
985
+ logger_1.logger.info(lang_1.lang.__('NESTED_SG_RULES_REPAIRED', {
986
+ securityGroupId: sgInstance.id,
987
+ added: String(missingIngress.length + missingEgress.length),
988
+ removed: String(extraIngress.length + extraEgress.length),
989
+ }));
990
+ }
991
+ catch (error) {
992
+ logger_1.logger.warn(lang_1.lang.__('NESTED_REPAIR_FAILED', { resource: sgInstance.id, error: String(error) }));
993
+ }
994
+ }
843
995
  }
844
996
  }
845
997
  if (fn.storage?.nas && fn.storage.nas.length > 0 && fn.network && !hasNasResources) {
846
- const deps = await createDependentResources(context, { ...fn, log: false }, serviceName, undefined, state, executionStatements);
998
+ // The SG branch above already created/reused the security group — pass it
999
+ // so the helper reuses it instead of creating an untracked duplicate.
1000
+ const sgExistingInstances = securityGroup
1001
+ ? [
1002
+ {
1003
+ type: 'ALIYUN_ECS_SECURITY_GROUP',
1004
+ id: securityGroup.securityGroupId,
1005
+ attributes: {},
1006
+ },
1007
+ ]
1008
+ : [];
1009
+ const deps = await createDependentResources(context, { ...fn, log: false }, serviceName, sgExistingInstances, state, { skipRole: true });
847
1010
  nasConfig = deps.nasConfig;
848
1011
  newDependentInstances.push(...deps.instances.filter((i) => i.type.startsWith('ALIYUN_NAS_')));
849
1012
  }
850
1013
  else if (hasNasResources) {
851
1014
  const mountTargetInstances = existingInstances.filter((i) => i.type === 'ALIYUN_NAS_MOUNT_TARGET');
852
1015
  const nasStorageItems = fn.storage?.nas ?? [];
1016
+ // Issue #234 M4: nested repair — only on a drifted plan item (force): a
1017
+ // file system with no live mount targets gets its mount target recreated
1018
+ // (console deletions); extra mount targets are left alone — deleting
1019
+ // shared infrastructure on a reconcile is never safe.
1020
+ if (options?.force && fn.network) {
1021
+ // Best-effort: a transient NAS read failure must not fail the update.
1022
+ let failingFsId;
1023
+ try {
1024
+ const fsInstances = existingInstances.filter((i) => i.type === 'ALIYUN_NAS_FILE_SYSTEM');
1025
+ for (const fsEntry of fsInstances) {
1026
+ failingFsId = fsEntry.id;
1027
+ const liveTargets = await client.nas.listMountTargets(fsEntry.id);
1028
+ if (!liveTargets || liveTargets.length === 0) {
1029
+ const mountPath = nasStorageItems[0]?.mount_path ?? '/mnt/nas';
1030
+ const accessGroupName = `${fn.name}-${context.stage}-nas-access-${mountPath}`;
1031
+ await client.nas.createMountTarget(fsEntry.id, accessGroupName, fn.network.vpc_id, fn.network.subnet_ids[0]);
1032
+ logger_1.logger.warn(lang_1.lang.__('NESTED_MOUNT_TARGET_RECREATED', { fileSystemId: fsEntry.id }));
1033
+ }
1034
+ }
1035
+ }
1036
+ catch (error) {
1037
+ logger_1.logger.warn(lang_1.lang.__('NESTED_REPAIR_FAILED', { resource: failingFsId ?? 'nas', error: String(error) }));
1038
+ }
1039
+ }
853
1040
  if (mountTargetInstances.length > 0 && nasStorageItems.length > 0) {
854
1041
  nasConfig = {
855
1042
  mountPoints: mountTargetInstances.map((mt, idx) => ({
@@ -906,7 +1093,10 @@ const updateResource = async (context, fn, state) => {
906
1093
  const { codeHash: _existingCodeHash, iam: _existingIam, ...existingConfigOnly } = existingConfig || {};
907
1094
  const { codeHash: _desiredCodeHash, ...desiredConfigOnly } = desiredDefinition;
908
1095
  const configChanged = !(0, common_1.attributesEqual)(existingConfigOnly, desiredConfigOnly);
909
- if (configChanged) {
1096
+ // `force` carries the plan's drifted flag: a live-drift update (state
1097
+ // matches config, cloud edited in console) must re-push the config even
1098
+ // though state-vs-desired sees no change.
1099
+ if (configChanged || roleBindingChanged || options?.force) {
910
1100
  await client.fc3.updateFunctionConfiguration(config);
911
1101
  }
912
1102
  if (codeChanged) {
@@ -1083,6 +1273,7 @@ const updateResource = async (context, fn, state) => {
1083
1273
  .filter((i) => i.type !== 'ALIYUN_FC3_HTTP_TRIGGER')
1084
1274
  .filter((i) => i.type !== 'ALIYUN_FC3_CUSTOM_DOMAIN')
1085
1275
  .filter((i) => !(typeof fn.iam?.role === 'string' && i.type === 'ALIYUN_RAM_ROLE'))
1276
+ .filter((i) => !(i.type === 'ALIYUN_RAM_ROLE' && droppedRamRoleIds.has(i.id)))
1086
1277
  .filter((i) => !droppedSlsDependentTypes.includes(i.type))
1087
1278
  .map((i) => {
1088
1279
  const { sid: existingSid, id: existingId, ...rest } = i;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractFunctionDomainDefinition = exports.extractFc3Definition = exports.functionToFc3Config = void 0;
3
+ exports.cloudFc3ToDefinition = exports.extractFunctionDomainDefinition = exports.extractFc3Definition = exports.functionToFc3Config = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const common_1 = require("../../common");
6
6
  const gpuConfigMap = {
@@ -93,3 +93,63 @@ const extractFunctionDomainDefinition = (fn, codeHash) => {
93
93
  return (0, exports.extractFc3Definition)(config, codeHash);
94
94
  };
95
95
  exports.extractFunctionDomainDefinition = extractFunctionDomainDefinition;
96
+ /**
97
+ * Cloud-side counterpart of extractFc3Definition (issue #234 live drift): maps
98
+ * a GetFunction response back to the desired-definition shape. Must mirror the
99
+ * executor's write shape (`functionToFc3Config`) key-for-key — keys the
100
+ * executor never writes (customContainerConfig entrypoint/accelerationType)
101
+ * are omitted entirely, and command/enableTls are emitted only when the cloud
102
+ * reports them, so image-level or provider-defaulted values can never
103
+ * phantom-drift against a config that does not declare them.
104
+ */
105
+ const cloudFc3ToDefinition = (info) => {
106
+ return {
107
+ functionName: info.functionName ?? null,
108
+ runtime: info.runtime ?? null,
109
+ handler: info.handler ?? null,
110
+ memorySize: info.memorySize ?? null,
111
+ timeout: info.timeout ?? null,
112
+ diskSize: info.diskSize ?? null,
113
+ environment: info.environmentVariables ?? {},
114
+ vpcConfig: info.vpcConfig
115
+ ? {
116
+ vpcId: info.vpcConfig.vpcId ?? null,
117
+ vSwitchIds: info.vpcConfig.vSwitchIds ?? [],
118
+ securityGroupId: info.vpcConfig.securityGroupId ?? null,
119
+ }
120
+ : null,
121
+ gpuConfig: info.gpuConfig
122
+ ? {
123
+ gpuMemorySize: info.gpuConfig.gpuMemorySize ?? null,
124
+ gpuType: info.gpuConfig.gpuType ?? null,
125
+ }
126
+ : null,
127
+ customContainerConfig: info.customContainerConfig
128
+ ? {
129
+ image: info.customContainerConfig.image ?? null,
130
+ port: info.customContainerConfig.port ?? null,
131
+ ...(info.customContainerConfig.command !== undefined
132
+ ? { command: info.customContainerConfig.command }
133
+ : {}),
134
+ }
135
+ : null,
136
+ nasConfig: info.nasConfig
137
+ ? {
138
+ userId: info.nasConfig.userId ?? null,
139
+ groupId: info.nasConfig.groupId ?? null,
140
+ mountPoints: (info.nasConfig.mountPoints ?? []).map((mp) => ({
141
+ serverAddr: mp.serverAddr ?? null,
142
+ mountDir: mp.mountDir ?? null,
143
+ enableTls: mp.enableTls ?? null,
144
+ })),
145
+ }
146
+ : null,
147
+ logConfig: info.logConfig
148
+ ? {
149
+ enableRequestMetrics: info.logConfig.enableRequestMetrics ?? null,
150
+ enableInstanceMetrics: info.logConfig.enableInstanceMetrics ?? null,
151
+ }
152
+ : null,
153
+ };
154
+ };
155
+ exports.cloudFc3ToDefinition = cloudFc3ToDefinition;
@@ -6,9 +6,12 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.generateBucketPlan = void 0;
7
7
  const node_path_1 = __importDefault(require("node:path"));
8
8
  const aliyunClient_1 = require("../../common/aliyunClient");
9
+ const refreshCache_1 = require("../../common/refreshCache");
10
+ const concurrency_1 = require("../../common/concurrency");
9
11
  const ossTypes_1 = require("./ossTypes");
10
12
  const stateManager_1 = require("../../common/stateManager");
11
13
  const hashUtils_1 = require("../../common/hashUtils");
14
+ const refreshPlanner_1 = require("../../common/refreshPlanner");
12
15
  const ownershipTag_1 = require("../ownershipTag");
13
16
  const planBucketDeletion = (logicalId, definition) => ({
14
17
  logicalId,
@@ -32,7 +35,7 @@ const generateBucketPlan = async (context, state, buckets) => {
32
35
  return { items };
33
36
  }
34
37
  const desiredLogicalIds = new Set(buckets.map((bucket) => `buckets.${bucket.key}`));
35
- const bucketItems = await Promise.all(buckets.map(async (bucket) => {
38
+ const bucketItems = await (0, concurrency_1.mapWithConcurrency)(buckets, concurrency_1.PLAN_READ_CONCURRENCY, async (bucket) => {
36
39
  const logicalId = `buckets.${bucket.key}`;
37
40
  const currentState = (0, stateManager_1.getResource)(state, logicalId);
38
41
  const config = (0, ossTypes_1.bucketToOssBucketConfig)(bucket);
@@ -47,68 +50,23 @@ const generateBucketPlan = async (context, state, buckets) => {
47
50
  }
48
51
  })();
49
52
  const desiredDefinition = (0, ossTypes_1.extractOssBucketDefinition)(config, websiteCodeHash);
50
- if (!currentState || currentState.status === 'tainted') {
51
- // No usable local state: probe the provider before planning create.
52
- // If a same-named bucket already exists WITHOUT our ownership tag it
53
- // may belong to another project — fail fast in the plan instead of
54
- // letting the executor discover it mid-deploy.
55
- const client = (0, aliyunClient_1.createAliyunClient)(context);
56
- const remoteBucket = await client.oss.getBucket(bucket.name);
57
- if (remoteBucket &&
58
- !(0, ownershipTag_1.isOwnedByStack)(context, logicalId, toOwnershipTags(remoteBucket.tags))) {
59
- throw new Error(`Bucket ${bucket.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`);
60
- }
61
- return {
62
- logicalId,
63
- action: 'create',
64
- resourceType: 'ALIYUN_OSS_BUCKET',
65
- changes: { after: desiredDefinition },
66
- };
67
- }
68
- try {
69
- const client = (0, aliyunClient_1.createAliyunClient)(context);
70
- const remoteBucket = await client.oss.getBucket(bucket.name);
71
- if (!remoteBucket) {
72
- return {
73
- logicalId,
74
- action: 'create',
75
- resourceType: 'ALIYUN_OSS_BUCKET',
76
- changes: {
77
- before: normalizeDefinitionForDisplay(currentState.definition),
78
- after: desiredDefinition,
79
- },
80
- drifted: true,
81
- };
82
- }
83
- const currentDefinition = currentState.definition || {};
84
- const normalizedCurrent = normalizeDefinitionForDisplay(currentDefinition);
85
- const normalizedDesired = normalizeDefinitionForDisplay(desiredDefinition);
86
- const { domainBound } = currentDefinition;
87
- const definitionChanged = !(0, hashUtils_1.attributesEqual)(normalizedCurrent, normalizedDesired);
88
- const domainBindingPending = domainBound === false;
89
- if (definitionChanged || domainBindingPending) {
90
- return {
91
- logicalId,
92
- action: 'update',
93
- resourceType: 'ALIYUN_OSS_BUCKET',
94
- changes: { before: normalizedCurrent, after: normalizedDesired },
95
- ...(definitionChanged ? { drifted: true } : {}),
96
- };
97
- }
98
- return { logicalId, action: 'noop', resourceType: 'ALIYUN_OSS_BUCKET' };
99
- }
100
- catch {
101
- return {
102
- logicalId,
103
- action: 'create',
104
- resourceType: 'ALIYUN_OSS_BUCKET',
105
- changes: {
106
- before: normalizeDefinitionForDisplay(currentState.definition),
107
- after: desiredDefinition,
108
- },
109
- };
110
- }
111
- }));
53
+ const client = (0, aliyunClient_1.createAliyunClient)(context);
54
+ const domainBindingPending = currentState?.definition?.domainBound ===
55
+ false;
56
+ return (0, refreshPlanner_1.planRefreshedResource)({
57
+ logicalId,
58
+ resourceType: 'ALIYUN_OSS_BUCKET',
59
+ currentState,
60
+ desiredDefinition,
61
+ read: () => (0, refreshCache_1.cachedRefreshRead)(context, `oss.getBucket:${bucket.name}`, () => client.oss.getBucket(bucket.name)),
62
+ isOwned: (remote) => (0, ownershipTag_1.isOwnedByStack)(context, logicalId, toOwnershipTags(remote.tags)),
63
+ foreignError: () => new Error(`Bucket ${bucket.name} already exists in provider but is not owned by this stack (missing ${ownershipTag_1.OWNERSHIP_TAG_KEY} tag). Refusing to create — resolve manually.`),
64
+ cloudToDefinition: ossTypes_1.cloudOssToDefinition,
65
+ normalizeForDisplay: normalizeDefinitionForDisplay,
66
+ extraUpdate: () => Promise.resolve({ update: domainBindingPending, drifted: false }),
67
+ refresh: context.refresh,
68
+ });
69
+ });
112
70
  const allStates = (0, stateManager_1.getAllResources)(state);
113
71
  const deletionItems = Object.entries(allStates)
114
72
  .filter(([logicalId]) => logicalId.startsWith('buckets.') && !desiredLogicalIds.has(logicalId))
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractOssBucketDefinition = exports.bucketToOssBucketConfig = void 0;
3
+ exports.cloudOssToDefinition = exports.extractOssBucketDefinition = exports.bucketToOssBucketConfig = void 0;
4
4
  const types_1 = require("../../types");
5
5
  const bucketTypes_1 = require("../bucketTypes");
6
6
  const aclMap = {
@@ -132,3 +132,27 @@ const extractOssBucketDefinition = (config, websiteCodeHash) => {
132
132
  return def;
133
133
  };
134
134
  exports.extractOssBucketDefinition = extractOssBucketDefinition;
135
+ const cloudOssToDefinition = (info) => ({
136
+ bucketName: info.name,
137
+ ...(info.acl !== undefined ? { acl: info.acl } : {}),
138
+ ...(info.websiteConfig
139
+ ? {
140
+ websiteConfiguration: {
141
+ indexDocument: info.websiteConfig.indexDocument,
142
+ errorDocument: info.websiteConfig.errorDocument ?? null,
143
+ },
144
+ }
145
+ : {}),
146
+ ...(info.storageClass !== undefined ? { storageClass: info.storageClass } : {}),
147
+ ...(info.versioningConfig?.status !== undefined
148
+ ? { versioningStatus: info.versioningConfig.status }
149
+ : {}),
150
+ ...(info.encryptionConfig?.sseAlgorithm !== undefined
151
+ ? { sseAlgorithm: info.encryptionConfig.sseAlgorithm }
152
+ : {}),
153
+ ...(info.policy !== undefined ? { policy: info.policy } : {}),
154
+ ...(typeof info.transferAccelerationStatus === 'boolean'
155
+ ? { accelerateEnabled: info.transferAccelerationStatus }
156
+ : {}),
157
+ });
158
+ exports.cloudOssToDefinition = cloudOssToDefinition;