@geek-fun/serverlessinsight 0.9.1 → 0.9.2

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 (58) 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 +2 -2
  4. package/.serverlessinsight/state-insight-poc-app-log-insight-poc-tencent-log.json.backup +3 -3
  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 +109 -0
  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 +2 -2
  11. package/.serverlessinsight/state-role-reconcile-test-app-role-reconcile-test-service.json.backup +3 -3
  12. package/CHANGELOG.md +17 -0
  13. package/README.md +76 -0
  14. package/README.zh-CN.md +67 -0
  15. package/codecov +0 -0
  16. package/codecov.SHA256SUM +1 -0
  17. package/codecov.SHA256SUM.sig +16 -0
  18. package/dist/package.json +1 -1
  19. package/dist/src/commands/index.js +75 -23
  20. package/dist/src/commands/plan.js +21 -1
  21. package/dist/src/commands/schema.js +24 -0
  22. package/dist/src/commands/show.js +64 -10
  23. package/dist/src/commands/validate.js +34 -2
  24. package/dist/src/common/aliyunClient/fc3Operations.js +32 -1
  25. package/dist/src/common/constants.js +7 -1
  26. package/dist/src/common/jsonOutput.js +77 -0
  27. package/dist/src/common/logger.js +6 -3
  28. package/dist/src/common/noColor.js +9 -0
  29. package/dist/src/common/planFormatter.js +12 -6
  30. package/dist/src/common/siCron.js +415 -0
  31. package/dist/src/common/stateBackend/saasStateBackend.js +5 -4
  32. package/dist/src/common/tencentClient/scfOperations.js +2 -0
  33. package/dist/src/common/volcengineClient/vefaasOperations.js +45 -0
  34. package/dist/src/lang/en.js +43 -0
  35. package/dist/src/lang/index.js +36 -1
  36. package/dist/src/lang/zh-CN.js +43 -0
  37. package/dist/src/parser/functionParser.js +47 -1
  38. package/dist/src/stack/aliyunStack/fc3Planner.js +26 -0
  39. package/dist/src/stack/aliyunStack/fc3Resource.js +159 -2
  40. package/dist/src/stack/localStack/event.js +2 -13
  41. package/dist/src/stack/localStack/function.js +2 -13
  42. package/dist/src/stack/localStack/index.js +8 -1
  43. package/dist/src/stack/localStack/timer.js +162 -0
  44. package/dist/src/stack/localStack/utils.js +19 -1
  45. package/dist/src/stack/scfStack/scfPlanner.js +52 -18
  46. package/dist/src/stack/scfStack/scfResource.js +170 -1
  47. package/dist/src/stack/volcengineStack/vefaasPlanner.js +49 -0
  48. package/dist/src/stack/volcengineStack/vefaasResource.js +215 -2
  49. package/dist/src/validator/functionSchema.js +25 -2
  50. package/dist/src/validator/iacSchema.js +2 -1
  51. package/dist/src/validator/index.js +4 -1
  52. package/dist/src/validator/rootSchema.js +49 -18
  53. package/dist/src/validator/schemaExport.js +60 -0
  54. package/dist/src/validator/semanticValidation.js +79 -0
  55. package/dist/src/validator/templateRefSchema.js +9 -1
  56. package/dist/tsconfig.tsbuildinfo +1 -1
  57. package/package.json +1 -1
  58. package/samples/aliyun-poc-timer.yml +39 -0
@@ -0,0 +1,162 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.stopLocalTimers = exports.startLocalTimers = exports.matchesNow = void 0;
7
+ const siCron_1 = require("../../common/siCron");
8
+ const aliyunFc_1 = require("./aliyunFc");
9
+ const utils_1 = require("./utils");
10
+ const functionRunner_1 = require("./functionRunner");
11
+ const common_1 = require("../../common");
12
+ const node_fs_1 = __importDefault(require("node:fs"));
13
+ const lang_1 = require("../../lang");
14
+ const timers = [];
15
+ const toSchedule = (cron) => {
16
+ try {
17
+ const parsed = (0, siCron_1.parseSiCron)(cron);
18
+ return parsed.kind === 'every'
19
+ ? { kind: 'every', intervalMs: parsed.totalSeconds * 1000 }
20
+ : { kind: 'cron', fields: parsed.fields, hasSeconds: parsed.hasSeconds };
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ };
26
+ const matchesField = (field, value) => field.wildcard || field.values.includes(value);
27
+ /** Pure UTC wall-clock match of a cron schedule against a point in time. */
28
+ const matchesNow = (schedule, now) => {
29
+ if (schedule.kind !== 'cron') {
30
+ return false; // @every is interval-driven, not wall-clock driven
31
+ }
32
+ const fields = schedule.fields;
33
+ if (!matchesField(fields.minute, now.getUTCMinutes())) {
34
+ return false;
35
+ }
36
+ if (!matchesField(fields.hour, now.getUTCHours())) {
37
+ return false;
38
+ }
39
+ if (!matchesField(fields.month, now.getUTCMonth() + 1)) {
40
+ return false;
41
+ }
42
+ // standard cron day semantics: both day fields restricted → OR (either may
43
+ // fire); at least one wildcard → the restricted side must match
44
+ const domRestricted = !fields.dayOfMonth.wildcard;
45
+ const dowRestricted = !fields.dayOfWeek.wildcard;
46
+ if (domRestricted && dowRestricted) {
47
+ const domHit = fields.dayOfMonth.values.includes(now.getUTCDate());
48
+ const dowHit = fields.dayOfWeek.values.includes(now.getUTCDay());
49
+ if (!domHit && !dowHit) {
50
+ return false;
51
+ }
52
+ }
53
+ else {
54
+ if (domRestricted && !fields.dayOfMonth.values.includes(now.getUTCDate())) {
55
+ return false;
56
+ }
57
+ if (dowRestricted && !fields.dayOfWeek.values.includes(now.getUTCDay())) {
58
+ return false;
59
+ }
60
+ }
61
+ if (schedule.hasSeconds && !matchesField(fields.second, now.getUTCSeconds())) {
62
+ return false;
63
+ }
64
+ return true;
65
+ };
66
+ exports.matchesNow = matchesNow;
67
+ const buildTimerEvent = (provider, triggerName, payload) => {
68
+ const triggerTime = new Date().toISOString();
69
+ if (provider === common_1.ProviderEnum.ALIYUN) {
70
+ // Aliyun FC timer event — the handler receives a Buffer of this JSON
71
+ return Buffer.from(JSON.stringify({ triggerName, triggerTime, payload }));
72
+ }
73
+ // Tencent SCF timer event shape (default for other providers)
74
+ return { Type: 'Timer', TriggerName: triggerName, Time: triggerTime, Message: payload };
75
+ };
76
+ const fireTimer = async (iac, fn, triggerName, payload) => {
77
+ if (!fn.code) {
78
+ return;
79
+ }
80
+ let tempDir = null;
81
+ try {
82
+ const resolved = await (0, utils_1.resolveCodeDir)(fn.code.path);
83
+ tempDir = resolved.tempDir;
84
+ const funOptions = {
85
+ codeDir: resolved.codeDir,
86
+ functionKey: fn.key,
87
+ handler: fn.code.handler,
88
+ servicePath: '',
89
+ timeout: (fn.timeout ?? 3) * 1000,
90
+ };
91
+ const event = buildTimerEvent(iac.provider.name, triggerName, payload);
92
+ const context = (0, aliyunFc_1.createAliyunContextSerializable)(iac, fn.name, fn.code.handler, fn.memory ?? 128, fn.timeout ?? 3, (0, aliyunFc_1.generateRequestId)());
93
+ common_1.logger.info(lang_1.lang.__('LOCAL_TIMER_FIRED', { triggerName, functionName: fn.name }));
94
+ const result = await (0, functionRunner_1.invokeFunction)(funOptions, { ...fn.environment }, event, context);
95
+ common_1.logger.info(lang_1.lang.__('FUNCTION_EXECUTION_RESULT', { result: JSON.stringify(result) }));
96
+ }
97
+ catch (error) {
98
+ common_1.logger.error(lang_1.lang.__('FUNCTION_EXECUTION_ERROR', { error: String(error) }));
99
+ }
100
+ finally {
101
+ if (tempDir && node_fs_1.default.existsSync(tempDir)) {
102
+ node_fs_1.default.rmSync(tempDir, { recursive: true, force: true });
103
+ }
104
+ }
105
+ };
106
+ const evaluateTimer = (iac, fn, triggerName, payload, schedule, state) => {
107
+ const now = new Date();
108
+ if (schedule.kind === 'every') {
109
+ if (Date.now() - state.lastFiredAt < schedule.intervalMs) {
110
+ return;
111
+ }
112
+ state.lastFiredAt = Date.now();
113
+ }
114
+ else {
115
+ // dedup to once per matching second (minute precision without seconds)
116
+ const tickKey = now.toISOString().slice(0, schedule.hasSeconds ? 19 : 16);
117
+ if (tickKey === state.lastTickKey || !(0, exports.matchesNow)(schedule, now)) {
118
+ return;
119
+ }
120
+ state.lastTickKey = tickKey;
121
+ }
122
+ if (state.running) {
123
+ return; // previous invocation still running — skip this tick
124
+ }
125
+ state.running = true;
126
+ void fireTimer(iac, fn, triggerName, payload).finally(() => {
127
+ state.running = false;
128
+ });
129
+ };
130
+ const startLocalTimers = (iac) => {
131
+ (0, exports.stopLocalTimers)();
132
+ iac.functions?.forEach((fn) => {
133
+ fn.triggers?.timer?.forEach((timer) => {
134
+ if (timer.enable === false) {
135
+ common_1.logger.info(lang_1.lang.__('LOCAL_TIMER_DISABLED', { triggerName: timer.name, functionName: fn.name }));
136
+ return;
137
+ }
138
+ const schedule = toSchedule(timer.cron);
139
+ if (!schedule) {
140
+ // unreachable for validated configs — the parser rejects bad si-cron
141
+ common_1.logger.warn(lang_1.lang.__('LOCAL_TIMER_INVALID_CRON', { triggerName: timer.name, cron: timer.cron }));
142
+ return;
143
+ }
144
+ common_1.logger.info(lang_1.lang.__('LOCAL_TIMER_SCHEDULED', {
145
+ triggerName: timer.name,
146
+ cron: timer.cron,
147
+ functionName: fn.name,
148
+ }));
149
+ const state = { lastTickKey: '', lastFiredAt: Date.now(), running: false };
150
+ const tick = setInterval(() => {
151
+ evaluateTimer(iac, fn, timer.name, timer.payload ?? '', schedule, state);
152
+ }, 1000);
153
+ timers.push(tick);
154
+ });
155
+ });
156
+ };
157
+ exports.startLocalTimers = startLocalTimers;
158
+ const stopLocalTimers = () => {
159
+ timers.forEach((tick) => clearInterval(tick));
160
+ timers.length = 0;
161
+ };
162
+ exports.stopLocalTimers = stopLocalTimers;
@@ -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.extractZipFile = void 0;
6
+ exports.resolveCodeDir = exports.extractZipFile = void 0;
7
7
  const jszip_1 = __importDefault(require("jszip"));
8
8
  const node_fs_1 = __importDefault(require("node:fs"));
9
9
  const node_path_1 = __importDefault(require("node:path"));
@@ -34,3 +34,21 @@ const extractZipFile = async (zipPath) => {
34
34
  return tempDir;
35
35
  };
36
36
  exports.extractZipFile = extractZipFile;
37
+ /**
38
+ * Resolve the handler directory from a function's configured code path:
39
+ * a zip artifact is extracted to a temp dir, a directory is used as-is,
40
+ * anything else falls back to its parent directory. Returns the temp dir
41
+ * so callers can clean it up after execution.
42
+ */
43
+ const resolveCodeDir = async (codePath) => {
44
+ const resolved = node_path_1.default.resolve(process.cwd(), codePath);
45
+ if (resolved.endsWith('.zip') && node_fs_1.default.existsSync(resolved)) {
46
+ const tempDir = await (0, exports.extractZipFile)(resolved);
47
+ return { codeDir: tempDir, tempDir };
48
+ }
49
+ if (node_fs_1.default.existsSync(resolved) && node_fs_1.default.statSync(resolved).isDirectory()) {
50
+ return { codeDir: resolved, tempDir: null };
51
+ }
52
+ return { codeDir: node_path_1.default.dirname(resolved), tempDir: null };
53
+ };
54
+ exports.resolveCodeDir = resolveCodeDir;
@@ -7,6 +7,7 @@ const lang_1 = require("../../lang");
7
7
  const refreshCache_1 = require("../../common/refreshCache");
8
8
  const clsOperations_1 = require("../../common/tencentClient/clsOperations");
9
9
  const concurrency_1 = require("../../common/concurrency");
10
+ const siCron_1 = require("../../common/siCron");
10
11
  const scfTypes_1 = require("./scfTypes");
11
12
  const stateManager_1 = require("../../common/stateManager");
12
13
  const hashUtils_1 = require("../../common/hashUtils");
@@ -61,26 +62,59 @@ const generateFunctionPlan = async (context, state, functions) => {
61
62
  // the skeleton's extraUpdate hook (issue #246) so a topic-only
62
63
  // drift gets the live→desired diff baseline too.
63
64
  const topicInstance = currentState?.instances?.find((i) => i.type === 'TENCENT_CLS_TOPIC');
64
- if (!fn.log || !topicInstance?.id) {
65
- return { update: false, drifted: false };
66
- }
67
- const topicId = topicInstance.id;
68
- try {
69
- const liveTopic = await (0, refreshCache_1.cachedRefreshRead)(context, `cls.getTopicById:${topicId}`, () => client.cls.getTopicById(topicId));
70
- const topicDrifted = !liveTopic ||
71
- liveTopic.StorageType !== clsOperations_1.CLS_TOPIC_STORAGE_TYPE ||
72
- liveTopic.Period !== clsOperations_1.CLS_TOPIC_PERIOD;
73
- return topicDrifted
74
- ? { update: true, drifted: true, reason: 'PLAN_DRIFT_CLS_TOPIC' }
75
- : { update: false, drifted: false };
65
+ if (fn.log && topicInstance?.id) {
66
+ const topicId = topicInstance.id;
67
+ try {
68
+ const liveTopic = await (0, refreshCache_1.cachedRefreshRead)(context, `cls.getTopicById:${topicId}`, () => client.cls.getTopicById(topicId));
69
+ const topicDrifted = !liveTopic ||
70
+ liveTopic.StorageType !== clsOperations_1.CLS_TOPIC_STORAGE_TYPE ||
71
+ liveTopic.Period !== clsOperations_1.CLS_TOPIC_PERIOD;
72
+ if (topicDrifted) {
73
+ return { update: true, drifted: true, reason: 'PLAN_DRIFT_CLS_TOPIC' };
74
+ }
75
+ }
76
+ catch (error) {
77
+ logger_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_NESTED_PROBE_FAILED', {
78
+ functionName: fn.name,
79
+ error: String(error),
80
+ }));
81
+ }
76
82
  }
77
- catch (error) {
78
- logger_1.logger.warn(lang_1.lang.__('PLAN_FUNCTION_NESTED_PROBE_FAILED', {
79
- functionName: fn.name,
80
- error: String(error),
81
- }));
82
- return { update: false, drifted: false };
83
+ // Issue #258: timer trigger drift — the live GetFunction trigger
84
+ // list is compared against the desired timers (name-keyed). The
85
+ // read is refresh-cached, so this reuses the fetch the skeleton
86
+ // already made. Manual deletes, console cron edits and extra
87
+ // triggers all mark the function drifted.
88
+ const timerStateInstances = (currentState?.instances ?? []).filter((i) => i.type === 'TENCENT_SCF_TIMER_TRIGGER');
89
+ const desiredTimers = fn.triggers?.timer ?? [];
90
+ if (desiredTimers.length > 0 || timerStateInstances.length > 0) {
91
+ try {
92
+ const live = await (0, refreshCache_1.cachedRefreshRead)(context, `scf.getFunction:${fn.name}`, () => client.scf.getFunction(fn.name));
93
+ const liveTimers = (live?.Triggers ?? []).filter((trigger) => trigger.Type === 'timer' && trigger.TriggerName);
94
+ const desiredNames = new Set(desiredTimers.map((timer) => timer.name));
95
+ const extraTimer = liveTimers.some((trigger) => !desiredNames.has(trigger.TriggerName));
96
+ const desiredChanged = desiredTimers.some((timer) => {
97
+ const liveTimer = liveTimers.find((trigger) => trigger.TriggerName === timer.name);
98
+ if (!liveTimer) {
99
+ return true;
100
+ }
101
+ // GetFunction reports Enable as 1/0
102
+ return (liveTimer.TriggerDesc !== (0, siCron_1.translateSiCron)(timer.cron, 'tencent') ||
103
+ (liveTimer.CustomArgument ?? undefined) !== timer.payload ||
104
+ (liveTimer.Enable === 1) !== timer.enable);
105
+ });
106
+ if (extraTimer || desiredChanged) {
107
+ return { update: true, drifted: true, reason: 'PLAN_DRIFT_TIMER_TRIGGER' };
108
+ }
109
+ }
110
+ catch (error) {
111
+ logger_1.logger.warn(lang_1.lang.__('PLAN_TIMER_TRIGGER_PROBE_FAILED', {
112
+ functionName: fn.name,
113
+ error: String(error),
114
+ }));
115
+ }
83
116
  }
117
+ return { update: false, drifted: false };
84
118
  },
85
119
  cloudToDefinition: scfTypes_1.cloudScfToDefinition,
86
120
  enrichRemoteAttributes: async (remote, attributes) => {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.deleteResource = exports.updateResource = exports.readResource = exports.createResource = exports.deriveScfExecutionStatements = void 0;
4
4
  const types_1 = require("../../types");
5
+ const siCron_1 = require("../../common/siCron");
5
6
  const tencentClient_1 = require("../../common/tencentClient");
6
7
  const fileUtils_1 = require("../../common/fileUtils");
7
8
  const scfTypes_1 = require("./scfTypes");
@@ -35,6 +36,148 @@ const buildTencentTriggerDesc = (authType, netConfig) => JSON.stringify({
35
36
  // Function URL trigger is identified by Type 'http' + a TriggerDesc carrying
36
37
  // the NetConfig field (the API Gateway flavor uses api/service/release instead).
37
38
  const isFunctionUrlTrigger = (t) => t.Type === 'http' && typeof t.TriggerDesc === 'string' && t.TriggerDesc.includes('NetConfig');
39
+ const TIMER_TRIGGER_INSTANCE_TYPE = 'TENCENT_SCF_TIMER_TRIGGER';
40
+ /** Tencent timer dialect: 7-field cron (UTC+8, `*` year), payload → CustomArgument. */
41
+ const buildScfTimerTriggerConfig = (timer) => ({
42
+ cron: (0, siCron_1.translateSiCron)(timer.cron, 'tencent'),
43
+ ...(timer.payload !== undefined ? { payload: timer.payload } : {}),
44
+ enable: timer.enable,
45
+ ...(timer.description !== undefined ? { description: timer.description } : {}),
46
+ });
47
+ const normalizeScfLiveTimerConfig = (trigger) => ({
48
+ cron: trigger.TriggerDesc ?? '',
49
+ ...(trigger.CustomArgument !== undefined && trigger.CustomArgument !== ''
50
+ ? { payload: trigger.CustomArgument }
51
+ : {}),
52
+ enable: trigger.Enable === 1 || trigger.Enable === 'OPEN',
53
+ ...(trigger.Description ? { description: trigger.Description } : {}),
54
+ });
55
+ const scfTimerConfigFromAttributes = (attrs) => {
56
+ const cron = typeof attrs.cron === 'string' ? attrs.cron : undefined;
57
+ if (!cron) {
58
+ return null;
59
+ }
60
+ try {
61
+ return {
62
+ cron: (0, siCron_1.translateSiCron)(cron, 'tencent'),
63
+ ...(attrs.payload !== undefined ? { payload: String(attrs.payload) } : {}),
64
+ enable: attrs.enable !== false,
65
+ ...(attrs.description !== undefined ? { description: String(attrs.description) } : {}),
66
+ };
67
+ }
68
+ catch {
69
+ return null;
70
+ }
71
+ };
72
+ const buildScfTimerTriggerInstance = (context, fn, timer) => ({
73
+ sid: (0, common_1.buildSid)('tencent', 'scf-timer-trigger', context.stage, `${fn.name}.${timer.name}`),
74
+ type: TIMER_TRIGGER_INSTANCE_TYPE,
75
+ id: timer.name,
76
+ cron: timer.cron,
77
+ ...(timer.payload !== undefined ? { payload: timer.payload } : {}),
78
+ enable: timer.enable,
79
+ ...(timer.description !== undefined ? { description: timer.description } : {}),
80
+ });
81
+ const deleteScfTimerTrigger = async (fnName, triggerName, client) => {
82
+ try {
83
+ await client.scf.deleteTrigger({
84
+ FunctionName: fnName,
85
+ TriggerName: triggerName,
86
+ Type: 'timer',
87
+ });
88
+ logger_1.logger.info(lang_1.lang.__('TIMER_TRIGGER_DELETED', { triggerName }));
89
+ return true;
90
+ }
91
+ catch (err) {
92
+ const errorCode = err?.code;
93
+ if (errorCode === 'ResourceNotFound.TriggerName' || errorCode === 'ResourceNotFound') {
94
+ logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_NOT_FOUND', { triggerName }));
95
+ return true;
96
+ }
97
+ throw err;
98
+ }
99
+ };
100
+ /**
101
+ * Reconcile the function's timer triggers against the provider (issue #258).
102
+ *
103
+ * The live trigger list from GetFunction is the reconcile baseline, so
104
+ * console-side cron edits, manual deletions and extra triggers converge on
105
+ * every deploy. When the probe fails the state-recorded instances take over.
106
+ * Name is the drift key; si-cron stays stored and is translated only here.
107
+ */
108
+ const reconcileScfTimerTriggers = async (context, fn, previousInstances, client) => {
109
+ const desiredTimers = fn.triggers?.timer ?? [];
110
+ const previousTimers = previousInstances.filter((i) => i.type === TIMER_TRIGGER_INSTANCE_TYPE);
111
+ if (desiredTimers.length === 0 && previousTimers.length === 0) {
112
+ return [];
113
+ }
114
+ let liveTimers = [];
115
+ let liveAvailable = true;
116
+ try {
117
+ const probe = await client.scf.getFunction(fn.name);
118
+ liveTimers = (probe?.Triggers ?? [])
119
+ .filter((trigger) => trigger.Type === 'timer' && trigger.TriggerName)
120
+ .map((trigger) => ({
121
+ name: trigger.TriggerName,
122
+ config: normalizeScfLiveTimerConfig(trigger),
123
+ }));
124
+ }
125
+ catch (error) {
126
+ liveAvailable = false;
127
+ logger_1.logger.warn(lang_1.lang.__('PLAN_TIMER_TRIGGER_PROBE_FAILED', { functionName: fn.name, error: String(error) }));
128
+ }
129
+ const baseline = liveAvailable
130
+ ? liveTimers
131
+ : previousTimers.flatMap((instance) => {
132
+ const config = scfTimerConfigFromAttributes(instance);
133
+ return config ? [{ name: String(instance.id), config }] : [];
134
+ });
135
+ const resultingInstances = [];
136
+ for (const timer of desiredTimers) {
137
+ const desiredConfig = buildScfTimerTriggerConfig(timer);
138
+ const live = baseline.find((entry) => entry.name === timer.name);
139
+ if (!live) {
140
+ logger_1.logger.info(lang_1.lang.__('CREATING_TIMER_TRIGGER', { triggerName: timer.name, functionName: fn.name }));
141
+ }
142
+ else if (!(0, common_1.attributesEqual)(live.config, desiredConfig)) {
143
+ logger_1.logger.info(lang_1.lang.__('UPDATING_TIMER_TRIGGER', { triggerName: timer.name, functionName: fn.name }));
144
+ await deleteScfTimerTrigger(fn.name, timer.name, client);
145
+ }
146
+ else {
147
+ resultingInstances.push(buildScfTimerTriggerInstance(context, fn, timer));
148
+ continue;
149
+ }
150
+ try {
151
+ await client.scf.createTrigger({
152
+ FunctionName: fn.name,
153
+ TriggerName: timer.name,
154
+ Type: 'timer',
155
+ TriggerDesc: desiredConfig.cron,
156
+ ...(desiredConfig.payload !== undefined ? { CustomArgument: desiredConfig.payload } : {}),
157
+ Qualifier: '$DEFAULT',
158
+ Enable: desiredConfig.enable ? 'OPEN' : 'CLOSE',
159
+ ...(desiredConfig.description ? { Description: desiredConfig.description } : {}),
160
+ });
161
+ }
162
+ catch (error) {
163
+ // a leftover trigger from an adopted function may already carry the name
164
+ if (!(0, alreadyExists_1.isResourceAlreadyExistsError)(error))
165
+ throw error;
166
+ logger_1.logger.warn(lang_1.lang.__('TIMER_TRIGGER_ALREADY_ATTACHED', {
167
+ triggerName: timer.name,
168
+ functionName: fn.name,
169
+ }));
170
+ }
171
+ logger_1.logger.info(lang_1.lang.__('TIMER_TRIGGER_CREATED', { triggerName: timer.name, functionName: fn.name }));
172
+ resultingInstances.push(buildScfTimerTriggerInstance(context, fn, timer));
173
+ }
174
+ const desiredNames = new Set(desiredTimers.map((timer) => timer.name));
175
+ for (const stale of baseline.filter((entry) => !desiredNames.has(entry.name))) {
176
+ logger_1.logger.info(lang_1.lang.__('DELETING_TIMER_TRIGGER', { triggerName: stale.name, functionName: fn.name }));
177
+ await deleteScfTimerTrigger(fn.name, stale.name, client);
178
+ }
179
+ return resultingInstances;
180
+ };
38
181
  /**
39
182
  * Best-effort extraction of a cloud-SDK error's useful details. Tencent SDK
40
183
  * errors carry `code`/`message`/`requestId` (and may throw with an empty
@@ -612,6 +755,18 @@ const createResource = async (context, fn, state) => {
612
755
  }
613
756
  }
614
757
  }
758
+ // Create timer triggers if configured — a failure mid-way persists the
759
+ // tainted state so a re-run reconciles instead of duplicating triggers.
760
+ if (fn.triggers?.timer) {
761
+ try {
762
+ dependentInstances.push(...(await reconcileScfTimerTriggers(context, fn, [], client)));
763
+ }
764
+ catch (error) {
765
+ if (error instanceof types_1.PartialResourceError)
766
+ throw error;
767
+ throw new types_1.PartialResourceError(stateAfterDependents, new Error(toErrorMessage(error)));
768
+ }
769
+ }
615
770
  // Create custom domain if configured
616
771
  if (fn.domain) {
617
772
  logger_1.logger.info(lang_1.lang.__('CREATING_CUSTOM_DOMAIN', { domainName: fn.domain.domain_name }));
@@ -982,6 +1137,9 @@ const updateResource = async (context, fn, state, options) => {
982
1137
  }
983
1138
  }
984
1139
  }
1140
+ // Reconcile timer triggers against the provider (issue #258) — the live
1141
+ // GetFunction trigger list is the baseline so console edits converge.
1142
+ const timerInstances = await reconcileScfTimerTriggers(context, fn, existingInstances, client);
985
1143
  // Reconcile custom domain
986
1144
  const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
987
1145
  if (fn.domain && !existingCustomDomain) {
@@ -1057,6 +1215,8 @@ const updateResource = async (context, fn, state, options) => {
1057
1215
  const existingDependentInstances = existingInstances
1058
1216
  .filter((i) => i.type !== undefined &&
1059
1217
  i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN' &&
1218
+ // timers are fully rebuilt from the reconcile result below
1219
+ i.type !== TIMER_TRIGGER_INSTANCE_TYPE &&
1060
1220
  !((clsTopicInstance || disableLog) &&
1061
1221
  (i.type === types_1.ResourceTypeEnum.TENCENT_CLS_TOPIC ||
1062
1222
  i.type === types_1.ResourceTypeEnum.TENCENT_CLS_LOGSET)))
@@ -1100,6 +1260,7 @@ const updateResource = async (context, fn, state, options) => {
1100
1260
  buildScfInstanceFromProvider(functionInfo, sid),
1101
1261
  ...existingDependentInstances,
1102
1262
  ...newDependentInstances,
1263
+ ...timerInstances,
1103
1264
  ],
1104
1265
  lastUpdated: new Date().toISOString(),
1105
1266
  };
@@ -1141,6 +1302,12 @@ const deleteResource = async (context, functionName, logicalId, state) => {
1141
1302
  }
1142
1303
  }
1143
1304
  }
1305
+ // Delete timer triggers before deleting function
1306
+ const timerTriggerInstances = existingInstances.filter((i) => i.type === TIMER_TRIGGER_INSTANCE_TYPE);
1307
+ for (const timerInstance of timerTriggerInstances) {
1308
+ logger_1.logger.info(lang_1.lang.__('DELETING_TIMER_TRIGGER', { triggerName: timerInstance.id, functionName }));
1309
+ await deleteScfTimerTrigger(functionName, timerInstance.id, client);
1310
+ }
1144
1311
  // Delete custom domain before deleting function
1145
1312
  const existingCustomDomain = existingInstances.find((i) => i.type === 'TENCENT_SCF_CUSTOM_DOMAIN');
1146
1313
  if (existingCustomDomain) {
@@ -1178,7 +1345,9 @@ const deleteResource = async (context, functionName, logicalId, state) => {
1178
1345
  }
1179
1346
  }
1180
1347
  const dependentInstances = existingInstances.filter((i) => i.type !== undefined &&
1181
- i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN');
1348
+ i.type !== 'TENCENT_SCF_CUSTOM_DOMAIN' &&
1349
+ // timers were deleted explicitly above
1350
+ i.type !== TIMER_TRIGGER_INSTANCE_TYPE);
1182
1351
  if (dependentInstances.length > 0) {
1183
1352
  await deleteDependentResources(context, dependentInstances);
1184
1353
  }
@@ -7,6 +7,7 @@ const volcengineClient_1 = require("../../common/volcengineClient");
7
7
  const refreshCache_1 = require("../../common/refreshCache");
8
8
  const planCompare_1 = require("../../common/planCompare");
9
9
  const concurrency_1 = require("../../common/concurrency");
10
+ const siCron_1 = require("../../common/siCron");
10
11
  const vefaasTypes_1 = require("./vefaasTypes");
11
12
  const vefaasResource_1 = require("./vefaasResource");
12
13
  const tlsOperations_1 = require("../../common/volcengineClient/tlsOperations");
@@ -270,6 +271,54 @@ const generateFunctionPlan = async (context, state, functions) => {
270
271
  }
271
272
  }
272
273
  }
274
+ // Issue #258: timer trigger drift — the live trigger list is compared
275
+ // against the desired timers (name-keyed). A trigger missing from the
276
+ // cloud (manual delete), an edited source config, or an extra
277
+ // undeclared timer all count as drift.
278
+ const timerStateInstances = currentState.instances.filter((i) => i.type === 'VOLCENGINE_VEFAAS_TIMER_TRIGGER');
279
+ const desiredTimers = fn.triggers?.timer ?? [];
280
+ if ((desiredTimers.length > 0 || timerStateInstances.length > 0) &&
281
+ remoteFunction.functionId) {
282
+ try {
283
+ const liveTriggers = await (0, refreshCache_1.cachedRefreshRead)(context, `vefaas.listTriggers:${remoteFunction.functionId}`, () => client.vefaas.listTriggers(remoteFunction.functionId));
284
+ const liveTimers = liveTriggers.filter((trigger) => trigger.sourceType?.toLowerCase() === 'timer');
285
+ const desiredNames = new Set(desiredTimers.map((timer) => timer.name));
286
+ const extraTimer = liveTimers.some((trigger) => !trigger.name || !desiredNames.has(trigger.name));
287
+ const desiredChanged = desiredTimers.some((timer) => {
288
+ const live = liveTimers.find((trigger) => trigger.name === timer.name);
289
+ if (!live) {
290
+ return true;
291
+ }
292
+ let source;
293
+ try {
294
+ source = JSON.parse(live.source ?? '{}');
295
+ }
296
+ catch {
297
+ return true;
298
+ }
299
+ return (source.cron !== (0, siCron_1.translateSiCron)(timer.cron, 'volcengine') ||
300
+ source.enable !== timer.enable ||
301
+ (source.payload ?? undefined) !== timer.payload ||
302
+ (source.description ?? undefined) !== timer.description);
303
+ });
304
+ if (extraTimer || desiredChanged) {
305
+ return {
306
+ logicalId,
307
+ action: 'update',
308
+ resourceType: 'VOLCENGINE_VEFAAS',
309
+ changes: { before: liveBefore, after: desiredDefinition },
310
+ drifted: true,
311
+ driftReasons: ['PLAN_DRIFT_TIMER_TRIGGER'],
312
+ };
313
+ }
314
+ }
315
+ catch (error) {
316
+ common_1.logger.warn(lang_1.lang.__('PLAN_TIMER_TRIGGER_PROBE_FAILED', {
317
+ functionName: fn.name,
318
+ error: String(error),
319
+ }));
320
+ }
321
+ }
273
322
  return { logicalId, action: 'noop', resourceType: 'VOLCENGINE_VEFAAS' };
274
323
  }
275
324
  catch (error) {