@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,9 +1,42 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
2
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
37
  };
5
38
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.diffAttributes = exports.attributesEqual = exports.computeDirectoryHash = exports.computeFileHash = void 0;
39
+ exports.diffAttributes = exports.attributesEqual = exports.computeDirectoryHash = exports.computeZipContentHash = exports.computeFileHash = void 0;
7
40
  const node_crypto_1 = __importDefault(require("node:crypto"));
8
41
  const node_fs_1 = __importDefault(require("node:fs"));
9
42
  const node_path_1 = __importDefault(require("node:path"));
@@ -13,6 +46,30 @@ const computeFileHash = (filePath) => {
13
46
  return node_crypto_1.default.createHash('sha256').update(fileBuffer).digest('hex');
14
47
  };
15
48
  exports.computeFileHash = computeFileHash;
49
+ /**
50
+ * Content-based hash of a ZIP archive: hashes each entry's path + bytes in
51
+ * sorted order, ignoring the archive binary itself. ZIP binaries embed file
52
+ * timestamps and ordering, so hashing the raw file yields a different value
53
+ * every time the same sources are repackaged — which makes every deploy plan
54
+ * show a phantom code update. Entry paths are sorted so archive ordering does
55
+ * not affect the result either.
56
+ */
57
+ const computeZipContentHash = async (zipPath) => {
58
+ const { default: JSZip } = await Promise.resolve().then(() => __importStar(require('jszip')));
59
+ const data = await node_fs_1.default.promises.readFile(zipPath);
60
+ const zip = await JSZip.loadAsync(data);
61
+ const entries = Object.values(zip.files)
62
+ .filter((entry) => !entry.dir)
63
+ .map((entry) => ({ path: entry.name, content: entry.async('nodebuffer') }));
64
+ entries.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
65
+ const hash = node_crypto_1.default.createHash('sha256');
66
+ for (const entry of entries) {
67
+ hash.update(entry.path);
68
+ hash.update(await entry.content);
69
+ }
70
+ return hash.digest('hex');
71
+ };
72
+ exports.computeZipContentHash = computeZipContentHash;
16
73
  /* istanbul ignore next */
17
74
  const computeDirectoryHash = (dirPath) => {
18
75
  const files = [];
@@ -47,7 +104,18 @@ exports.computeDirectoryHash = computeDirectoryHash;
47
104
  * @param b - Second value
48
105
  * @returns True if values are deeply equal, false otherwise
49
106
  */
50
- const deepEqual = (a, b) => {
107
+ const deepEqual = (a, b, options) => {
108
+ const { nullEqualsUndefined = false } = options ?? {};
109
+ // null and undefined both represent "unset" — treat them as equal when
110
+ // requested. Resource attribute comparison (plans, drift detection) relies
111
+ // on this because provider APIs return `null` for unset fields while
112
+ // desired definitions carry `undefined`.
113
+ if (nullEqualsUndefined) {
114
+ if (a === null && b === undefined)
115
+ return true;
116
+ if (a === undefined && b === null)
117
+ return true;
118
+ }
51
119
  // Handle primitives and null/undefined
52
120
  if (a === b) {
53
121
  return true;
@@ -73,7 +141,7 @@ const deepEqual = (a, b) => {
73
141
  return false;
74
142
  }
75
143
  for (let i = 0; i < objA.length; i++) {
76
- if (!deepEqual(objA[i], objB[i])) {
144
+ if (!deepEqual(objA[i], objB[i], options)) {
77
145
  return false;
78
146
  }
79
147
  }
@@ -83,9 +151,13 @@ const deepEqual = (a, b) => {
83
151
  if (Array.isArray(objA) || Array.isArray(objB)) {
84
152
  return false;
85
153
  }
86
- // Compare object keys
87
- const keysA = Object.keys(objA);
88
- const keysB = Object.keys(objB);
154
+ // Compare object keys. With nullEqualsUndefined, keys whose value is
155
+ // undefined (or null, which the option treats as equivalent) are treated as
156
+ // absent — JSON serialization drops undefined keys, so a state round-trip
157
+ // would otherwise look like a phantom added/removed.
158
+ const normalizeKey = (key, obj) => nullEqualsUndefined && (obj[key] === undefined || obj[key] === null);
159
+ const keysA = Object.keys(objA).filter((k) => !normalizeKey(k, objA));
160
+ const keysB = Object.keys(objB).filter((k) => !normalizeKey(k, objB));
89
161
  if (keysA.length !== keysB.length) {
90
162
  return false;
91
163
  }
@@ -94,7 +166,7 @@ const deepEqual = (a, b) => {
94
166
  if (!Object.prototype.hasOwnProperty.call(objB, key)) {
95
167
  return false;
96
168
  }
97
- if (!deepEqual(objA[key], objB[key])) {
169
+ if (!deepEqual(objA[key], objB[key], options)) {
98
170
  return false;
99
171
  }
100
172
  }
@@ -109,7 +181,7 @@ const deepEqual = (a, b) => {
109
181
  */
110
182
  /* istanbul ignore next */
111
183
  const attributesEqual = (a, b) => {
112
- return deepEqual(a, b);
184
+ return deepEqual(a, b, { nullEqualsUndefined: true });
113
185
  };
114
186
  exports.attributesEqual = attributesEqual;
115
187
  /**
@@ -129,14 +201,18 @@ const diffAttributes = (before, after) => {
129
201
  const beforeVal = before[key];
130
202
  const afterVal = after[key];
131
203
  if (!(key in before)) {
132
- added[key] = afterVal;
204
+ // JSON serialization drops undefined keys — a key absent on one side
205
+ // whose counterpart is undefined/null is not a real difference.
206
+ if (afterVal !== undefined && afterVal !== null)
207
+ added[key] = afterVal;
133
208
  }
134
209
  else if (!(key in after)) {
135
- removed[key] = beforeVal;
210
+ if (beforeVal !== undefined && beforeVal !== null)
211
+ removed[key] = beforeVal;
136
212
  }
137
213
  else {
138
214
  // Both exist - check if they're different using deep equality
139
- if (!deepEqual(beforeVal, afterVal)) {
215
+ if (!deepEqual(beforeVal, afterVal, { nullEqualsUndefined: true })) {
140
216
  changed[key] = { before: beforeVal, after: afterVal };
141
217
  }
142
218
  }
@@ -46,6 +46,7 @@ const getIamInfo = async (context) => {
46
46
  accessKeyId: context.accessKeyId,
47
47
  accessKeySecret: context.accessKeySecret,
48
48
  regionId: context.region,
49
+ endpoint: 'ims.aliyuncs.com',
49
50
  });
50
51
  imsConfig.connectTimeout = constants_1.ALIYUN_FC3_CONNECT_TIMEOUT_MS;
51
52
  imsConfig.readTimeout = constants_1.ALIYUN_FC3_READ_TIMEOUT_MS;
@@ -33,3 +33,6 @@ __exportStar(require("./dependencyGraph"), exports);
33
33
  __exportStar(require("./sidUtils"), exports);
34
34
  __exportStar(require("./certUtils"), exports);
35
35
  __exportStar(require("./planFormatter"), exports);
36
+ __exportStar(require("./credentialStore"), exports);
37
+ __exportStar(require("./apiClient"), exports);
38
+ __exportStar(require("./triggerMapper"), exports);
@@ -13,6 +13,7 @@ const constants_1 = require("./constants");
13
13
  const lang_1 = require("../lang");
14
14
  const logger_1 = require("./logger");
15
15
  class LockError extends Error {
16
+ lockInfo;
16
17
  constructor(message, lockInfo) {
17
18
  super(message);
18
19
  this.lockInfo = lockInfo;
@@ -20,12 +21,10 @@ class LockError extends Error {
20
21
  }
21
22
  }
22
23
  exports.LockError = LockError;
23
- /* istanbul ignore next */
24
24
  const getLockPath = (statePath) => {
25
25
  return `${statePath}${constants_1.LOCK_FILE_SUFFIX}`;
26
26
  };
27
27
  exports.getLockPath = getLockPath;
28
- /* istanbul ignore next */
29
28
  const generateLockId = () => {
30
29
  return node_crypto_1.default.randomBytes(16).toString('hex');
31
30
  };
@@ -71,13 +70,6 @@ const readLockFile = (lockPath) => {
71
70
  }
72
71
  return null;
73
72
  };
74
- const writeLockFile = (lockPath, metadata) => {
75
- const lockDir = node_path_1.default.dirname(lockPath);
76
- if (!node_fs_1.default.existsSync(lockDir)) {
77
- node_fs_1.default.mkdirSync(lockDir, { recursive: true });
78
- }
79
- node_fs_1.default.writeFileSync(lockPath, JSON.stringify(metadata, null, 2), 'utf-8');
80
- };
81
73
  const removeLockFile = (lockPath) => {
82
74
  if (node_fs_1.default.existsSync(lockPath)) {
83
75
  node_fs_1.default.unlinkSync(lockPath);
@@ -119,7 +111,6 @@ const getTimeAgo = (acquiredAt) => {
119
111
  }
120
112
  }
121
113
  };
122
- /* istanbul ignore next */
123
114
  const formatLockInfo = (lock) => {
124
115
  const acquiredAt = new Date(lock.acquiredAt);
125
116
  const timeAgo = getTimeAgo(acquiredAt);
@@ -137,7 +128,6 @@ exports.formatLockInfo = formatLockInfo;
137
128
  const sleep = (ms) => {
138
129
  return new Promise((resolve) => setTimeout(resolve, ms));
139
130
  };
140
- /* istanbul ignore next */
141
131
  const acquireLockInternal = async (statePath, operation, options = {}) => {
142
132
  const timeout = options.timeout ?? constants_1.DEFAULT_LOCK_TIMEOUT;
143
133
  const retryDelay = options.retryDelay ?? constants_1.DEFAULT_LOCK_RETRY_DELAY;
@@ -147,51 +137,71 @@ const acquireLockInternal = async (statePath, operation, options = {}) => {
147
137
  const startTime = Date.now();
148
138
  let attempt = 0;
149
139
  while (attempt <= maxRetries) {
150
- // Check if lock file exists
151
- const existingLock = readLockFile(lockPath);
152
- if (!existingLock) {
153
- // No lock exists, try to acquire
140
+ try {
141
+ const lockDir = node_path_1.default.dirname(lockPath);
142
+ if (!node_fs_1.default.existsSync(lockDir)) {
143
+ node_fs_1.default.mkdirSync(lockDir, { recursive: true });
144
+ }
145
+ // Atomic O_EXCL create: fails with EEXIST if another process holds the
146
+ // lock, so two processes can never both acquire.
147
+ let fd = null;
154
148
  try {
155
- writeLockFile(lockPath, metadata);
156
- // Verify we got the lock by reading it back
157
- const verifyLock = readLockFile(lockPath);
158
- if (verifyLock && verifyLock.id === metadata.id) {
159
- return metadata;
160
- }
149
+ fd = node_fs_1.default.openSync(lockPath, 'wx');
150
+ node_fs_1.default.writeFileSync(fd, JSON.stringify(metadata, null, 2), 'utf-8');
151
+ node_fs_1.default.fsyncSync(fd);
161
152
  }
162
- catch {
163
- // Failed to write lock, will retry
153
+ finally {
154
+ if (fd !== null) {
155
+ node_fs_1.default.closeSync(fd);
156
+ }
164
157
  }
158
+ return metadata;
165
159
  }
166
- else {
167
- if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
168
- logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
169
- processId: String(existingLock.processId),
170
- hostname: existingLock.hostname,
160
+ catch (error) {
161
+ if (error.code !== 'EEXIST') {
162
+ // If we created the lock file but failed to finish writing it, remove
163
+ // the partial file so a later attempt can retry cleanly.
164
+ if (node_fs_1.default.existsSync(lockPath)) {
165
+ try {
166
+ node_fs_1.default.unlinkSync(lockPath);
167
+ }
168
+ catch {
169
+ // best-effort cleanup
170
+ }
171
+ }
172
+ throw error;
173
+ }
174
+ const existingLock = readLockFile(lockPath);
175
+ if (existingLock) {
176
+ if (existingLock.hostname === node_os_1.default.hostname() && !isProcessAlive(existingLock.processId)) {
177
+ logger_1.logger.info(lang_1.lang.__('LOCK_AUTO_RELEASED_DEAD_PROCESS', {
178
+ processId: String(existingLock.processId),
179
+ hostname: existingLock.hostname,
180
+ user: existingLock.user,
181
+ acquiredAt: existingLock.acquiredAt,
182
+ }));
183
+ removeLockFile(lockPath);
184
+ attempt++;
185
+ continue;
186
+ }
187
+ if (isLockStale(existingLock)) {
188
+ // Lock is stale, but we don't auto-remove it
189
+ // User must use force-unlock
190
+ throw new LockError(`State is currently locked (stale lock detected).\n${(0, exports.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
191
+ }
192
+ // Check if timeout exceeded
193
+ if (Date.now() - startTime >= timeout) {
194
+ throw new LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, exports.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
195
+ }
196
+ const acquiredAt = new Date(existingLock.acquiredAt);
197
+ const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
198
+ const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
199
+ logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
171
200
  user: existingLock.user,
172
- acquiredAt: existingLock.acquiredAt,
201
+ timeAgo,
202
+ attempt: String(attempt + 1),
173
203
  }));
174
- removeLockFile(lockPath);
175
- attempt++;
176
- continue;
177
- }
178
- if (isLockStale(existingLock)) {
179
- // Lock is stale, but we don't auto-remove it
180
- // User must use force-unlock
181
- throw new LockError(`State is currently locked (stale lock detected).\n${(0, exports.formatLockInfo)(existingLock)}\nThis lock appears to be stale. If you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
182
- }
183
- // Check if timeout exceeded
184
- if (Date.now() - startTime >= timeout) {
185
- throw new LockError(`Failed to acquire lock after ${timeout / 1000} seconds.\n${(0, exports.formatLockInfo)(existingLock)}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock.id}`, existingLock);
186
204
  }
187
- const acquiredAt = new Date(existingLock.acquiredAt);
188
- const minutesAgo = Math.floor((Date.now() - acquiredAt.getTime()) / 60000);
189
- const timeAgo = minutesAgo < 1 ? lang_1.lang.__('LOCK_TIME_AGO_LESS_THAN_MINUTE') : `${minutesAgo}m`;
190
- logger_1.logger.info(lang_1.lang.__('LOCK_WAITING', {
191
- user: existingLock.user,
192
- timeAgo,
193
- attempt: String(attempt + 1),
194
- }));
195
205
  }
196
206
  // Wait before retrying with exponential backoff
197
207
  const delay = Math.min(retryDelay * Math.pow(2, attempt), 30000); // Cap at 30 seconds
@@ -203,7 +213,6 @@ const acquireLockInternal = async (statePath, operation, options = {}) => {
203
213
  throw new LockError(`Failed to acquire lock.\n${existingLock ? (0, exports.formatLockInfo)(existingLock) : ''}\nIf you are certain no other operation is running, use:\n si force-unlock ${existingLock?.id || 'unknown'}`, existingLock || undefined);
204
214
  };
205
215
  exports.acquireLockInternal = acquireLockInternal;
206
- /* istanbul ignore next */
207
216
  const releaseLockInternal = (statePath, lockId) => {
208
217
  const lockPath = (0, exports.getLockPath)(statePath);
209
218
  const existingLock = readLockFile(lockPath);
@@ -213,7 +222,6 @@ const releaseLockInternal = (statePath, lockId) => {
213
222
  }
214
223
  };
215
224
  exports.releaseLockInternal = releaseLockInternal;
216
- /* istanbul ignore next */
217
225
  const forceUnlock = (statePath, lockId) => {
218
226
  const lockPath = (0, exports.getLockPath)(statePath);
219
227
  const existingLock = readLockFile(lockPath);
@@ -227,11 +235,11 @@ const forceUnlock = (statePath, lockId) => {
227
235
  return true;
228
236
  };
229
237
  exports.forceUnlock = forceUnlock;
230
- /* istanbul ignore next */
231
- const withLock = async (statePath, operation, fn, options) => {
238
+ const withLock = async (statePath, operation, fn, options, onLockAcquired) => {
232
239
  let lock = null;
233
240
  try {
234
241
  lock = await (0, exports.acquireLockInternal)(statePath, operation, options);
242
+ onLockAcquired?.(lock.id);
235
243
  return await fn();
236
244
  }
237
245
  finally {
@@ -242,7 +250,6 @@ const withLock = async (statePath, operation, fn, options) => {
242
250
  };
243
251
  exports.withLock = withLock;
244
252
  // Export only for forceUnlock command which needs to read lock info
245
- /* istanbul ignore next */
246
253
  const readLockFileForCommand = (statePath) => {
247
254
  const lockPath = (0, exports.getLockPath)(statePath);
248
255
  return readLockFile(lockPath);
@@ -65,6 +65,8 @@ const getSystemEncoding = () => {
65
65
  return 'utf8';
66
66
  };
67
67
  class EncodingTransformStream extends stream_1.Writable {
68
+ encoding;
69
+ formatLog;
68
70
  constructor(encoding) {
69
71
  super();
70
72
  this.encoding = encoding;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.pollUntil = exports.PollingTimeoutError = void 0;
4
+ const retryUtils_1 = require("./retryUtils");
5
+ class PollingTimeoutError extends Error {
6
+ ctx;
7
+ constructor(ctx) {
8
+ super(`Polling timed out: ${ctx.description} after ${ctx.attempts} attempts ` +
9
+ `× ${ctx.intervalMs}ms (last value: ${ctx.lastValue === undefined ? 'undefined' : JSON.stringify(ctx.lastValue)})`);
10
+ this.ctx = ctx;
11
+ this.name = 'PollingTimeoutError';
12
+ }
13
+ }
14
+ exports.PollingTimeoutError = PollingTimeoutError;
15
+ /**
16
+ * Generic polling primitive — the single wait implementation for async cloud
17
+ * resource creation (mirrors Terraform's StateChangeConf / Tencent Cloud's
18
+ * waitScfFunctionReady pattern).
19
+ *
20
+ * - fetch errors propagate immediately (callers detect error states by throwing
21
+ * from their fetch wrapper)
22
+ * - on timeout, throws PollingTimeoutError carrying the last observed value
23
+ * - requiredConsecutiveHits guards against eventually-consistent APIs returning
24
+ * stale state (the done state must be observed N times in a row)
25
+ */
26
+ const pollUntil = async (options) => {
27
+ const { description, fetch, isDone, intervalMs, maxAttempts, onProgress, requiredConsecutiveHits = 1, } = options;
28
+ let consecutiveHits = 0;
29
+ let lastValue = null;
30
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
31
+ lastValue = await fetch();
32
+ onProgress?.(lastValue, attempt, maxAttempts);
33
+ if (isDone(lastValue)) {
34
+ consecutiveHits++;
35
+ if (consecutiveHits >= requiredConsecutiveHits) {
36
+ return lastValue;
37
+ }
38
+ }
39
+ else {
40
+ consecutiveHits = 0;
41
+ }
42
+ if (attempt < maxAttempts) {
43
+ await (0, retryUtils_1.sleep)(intervalMs);
44
+ }
45
+ }
46
+ throw new PollingTimeoutError({
47
+ description,
48
+ lastValue,
49
+ attempts: maxAttempts,
50
+ maxAttempts,
51
+ intervalMs,
52
+ });
53
+ };
54
+ exports.pollUntil = pollUntil;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.reportResourceEvent = void 0;
4
+ /** ADR-005: emit a resource lifecycle event via context.reportEvent (no-op if unwired). */
5
+ const reportResourceEvent = (context, event) => {
6
+ context.reportEvent?.(event);
7
+ };
8
+ exports.reportResourceEvent = reportResourceEvent;
@@ -144,20 +144,19 @@ const mapRuntime = (standardRuntime, provider) => {
144
144
  return providerRuntime;
145
145
  };
146
146
  exports.mapRuntime = mapRuntime;
147
+ // Valid veFaaS runtimes per the official CreateFunction API reference:
148
+ // golang/v1, native/v1, nativejava8/v1, node14/v1, node20/v1, nodeprime14/v1,
149
+ // python3.12/v1, python3.8/v1, python3.9/v1
147
150
  const VOLCENGINE_NATIVE_RUNTIMES = [
148
- 'nodejs/v20',
149
- 'nodejs/v18',
150
- 'nodejs/v16',
151
- 'nodejs/v14',
152
- 'python/v3.12',
153
- 'python/v3.11',
154
- 'python/v3.10',
155
- 'python/v3.9',
156
151
  'golang/v1',
157
- 'java/v21',
158
- 'java/v17',
159
- 'java/v11',
160
- 'java/v8',
152
+ 'native/v1',
153
+ 'nativejava8/v1',
154
+ 'node14/v1',
155
+ 'node20/v1',
156
+ 'nodeprime14/v1',
157
+ 'python3.12/v1',
158
+ 'python3.8/v1',
159
+ 'python3.9/v1',
161
160
  ];
162
161
  const isRuntimeSupported = (runtime, provider) => {
163
162
  if (provider === providerEnum_1.ProviderEnum.VOLCENGINE) {
@@ -20,14 +20,23 @@ const providerEnum_1 = require("../providerEnum");
20
20
  const localStateBackend_1 = require("./localStateBackend");
21
21
  const ossStateBackend_1 = require("./ossStateBackend");
22
22
  const cosStateBackend_1 = require("./cosStateBackend");
23
+ const saasStateBackend_1 = require("./saasStateBackend");
23
24
  __exportStar(require("./types"), exports);
24
25
  __exportStar(require("./localStateBackend"), exports);
25
26
  __exportStar(require("./ossStateBackend"), exports);
26
27
  __exportStar(require("./cosStateBackend"), exports);
27
28
  __exportStar(require("./remoteStateBackend"), exports);
29
+ __exportStar(require("./saasStateBackend"), exports);
28
30
  __exportStar(require("./lockUtils"), exports);
29
31
  const createStateBackend = (backendConfig, context) => {
30
- if (!backendConfig || backendConfig.type === types_1.StateBackendType.LOCAL) {
32
+ // SaaS (default) — requires API key
33
+ if (!backendConfig || backendConfig.type === types_1.StateBackendType.SAAS) {
34
+ return (0, saasStateBackend_1.createSaasStateBackend)({
35
+ app: context.app,
36
+ service: context.service,
37
+ });
38
+ }
39
+ if (backendConfig.type === types_1.StateBackendType.LOCAL) {
31
40
  return (0, localStateBackend_1.createLocalStateBackend)(context.app, context.service, context.baseDir);
32
41
  }
33
42
  const bucketConfig = backendConfig;
@@ -25,7 +25,10 @@ const createLocalStateBackend = (app, service, baseDir = process.cwd()) => {
25
25
  readLock: async () => {
26
26
  return (0, lockManager_1.readLockFileForCommand)(statePath);
27
27
  },
28
- withLock: async (operation, fn, options) => {
28
+ withLock: async (operation, fn, options, onLockAcquired) => {
29
+ if (onLockAcquired) {
30
+ return (0, lockManager_1.withLock)(statePath, operation, fn, options, onLockAcquired);
31
+ }
29
32
  return (0, lockManager_1.withLock)(statePath, operation, fn, options);
30
33
  },
31
34
  };
@@ -6,6 +6,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.createRemoteStateBackend = void 0;
7
7
  const node_os_1 = __importDefault(require("node:os"));
8
8
  const types_1 = require("../../types");
9
+ const stateManager_1 = require("../stateManager");
9
10
  const constants_1 = require("../constants");
10
11
  const lockManager_1 = require("../lockManager");
11
12
  const logger_1 = require("../logger");
@@ -70,8 +71,9 @@ const createRemoteStateBackend = (adapter, config) => {
70
71
  loadState: async (provider, app, service, stage) => {
71
72
  const state = await adapter.read(config.key);
72
73
  if (state) {
73
- const stageResources = state.stages?.[stage]?.resources ?? {};
74
- return { ...state, resources: stageResources };
74
+ const migrated = (0, stateManager_1.migrateState)(state);
75
+ const stageResources = migrated.stages?.[stage]?.resources ?? {};
76
+ return { ...migrated, resources: stageResources };
75
77
  }
76
78
  return { version: types_1.CURRENT_STATE_VERSION, provider, app, service, stages: {}, resources: {} };
77
79
  },
@@ -100,7 +102,10 @@ const createRemoteStateBackend = (adapter, config) => {
100
102
  provider: state.provider,
101
103
  stages: {
102
104
  ...existing.stages,
103
- [stage]: { resources: state.resources },
105
+ [stage]: {
106
+ resources: state.resources,
107
+ shared: state.stages?.[stage]?.shared ?? existing.stages?.[stage]?.shared ?? {},
108
+ },
104
109
  },
105
110
  resources: state.resources,
106
111
  };
@@ -129,11 +134,12 @@ const createRemoteStateBackend = (adapter, config) => {
129
134
  readLock: async () => {
130
135
  return readLockObject();
131
136
  },
132
- withLock: async (operation, fn, options) => {
137
+ withLock: async (operation, fn, options, onLockAcquired) => {
133
138
  let lockId = null;
134
139
  try {
135
140
  const meta = await acquireLockObject(operation, options);
136
141
  lockId = meta.id;
142
+ onLockAcquired?.(lockId);
137
143
  return await fn();
138
144
  }
139
145
  finally {