@h-ai/scheduler 0.1.0-alpha9 → 1.0.0-beta.10

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.
package/dist/index.js CHANGED
@@ -1,19 +1,20 @@
1
1
  import { z } from 'zod';
2
- import { cache } from '@h-ai/cache';
3
- import { core, err, ok } from '@h-ai/core';
4
- import { reldb, BaseReldbCrudRepository } from '@h-ai/reldb';
5
- import { createHash } from 'crypto';
6
- import { Script } from 'vm';
2
+ import { core, ok, err, HaiCommonError } from '@h-ai/core';
3
+ import { migrateSchema, reldb, schemaColumns, BaseReldbCrudRepository } from '@h-ai/reldb';
4
+ import { randomUUID, createHash } from 'crypto';
5
+ import { isDeepStrictEqual } from 'util';
7
6
  import { Cron } from 'croner';
7
+ import { Script } from 'vm';
8
+ import { Worker } from 'worker_threads';
8
9
 
9
10
  // src/scheduler-config.ts
10
11
  var SchedulerConfigSchema = z.object({
11
- /** 是否启用数据库记录(默认 true,需要 @h-ai/reldb 已初始化) */
12
- enableDb: z.boolean().default(true),
12
+ /** 必须使用共享数据库保存执行状态;false 不再允许,需要先初始化 @h-ai/reldb。 */
13
+ enableDb: z.literal(true).default(true),
13
14
  /** 调度检查间隔,单位毫秒(默认 1000,即每秒检查一次) */
14
15
  tickInterval: z.number().int().min(100).default(1e3),
15
- /** 分布式锁过期时间,单位毫秒(默认 300000,即 5 分钟) */
16
- lockExpireMs: z.number().int().min(1e4).default(3e5),
16
+ /** 执行租约毫秒数(默认 300000,范围 1000–86400000),在途每三分之一周期续期。 */
17
+ leaseMs: z.number().int().min(1e3).max(864e5).default(3e5),
17
18
  /** 节点标识(默认自动生成 UUID,多节点部署时建议设置固定标识以便审计) */
18
19
  nodeId: z.string().min(1).optional(),
19
20
  /** 执行日志最大保留条数(启用 DB 时生效) */
@@ -21,6 +22,14 @@ var SchedulerConfigSchema = z.object({
21
22
  /** 执行日志保留天数(启用 DB 时生效) */
22
23
  retentionDays: z.number().int().min(1).optional()
23
24
  });
25
+ var TriggerTaskSchema = z.object({
26
+ source: z.string().max(255).optional(),
27
+ idempotencyKey: z.string().min(1).max(128).optional()
28
+ });
29
+ var ExecutionResolutionSchema = z.object({
30
+ status: z.enum(["success", "discarded"]),
31
+ expectedUpdatedAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER - 1)
32
+ });
24
33
 
25
34
  // messages/en-US.json
26
35
  var en_US_default = {
@@ -29,25 +38,73 @@ var en_US_default = {
29
38
  scheduler_initFailed: "Failed to initialize scheduler: {error}",
30
39
  scheduler_alreadyRunning: "Scheduler is already running",
31
40
  scheduler_notRunning: "Scheduler is not running",
41
+ scheduler_closing: "Scheduler is closing; task execution cancelled",
42
+ scheduler_definitionsChanged: "Task definitions changed during refresh; retry the operation",
43
+ scheduler_taskNoLongerDue: "Task {taskId} was removed, disabled, or rescheduled",
32
44
  scheduler_taskNotFound: "Task not found: {taskId}",
33
45
  scheduler_taskAlreadyExists: "Task already exists: {taskId}",
34
46
  scheduler_invalidCron: "Invalid cron expression: {expression}",
35
47
  scheduler_executionFailed: "Task execution failed: {error}",
36
48
  scheduler_jsExecutionFailed: "JS code execution failed: {error}",
49
+ scheduler_jsTimedOut: "JS task timed out after {timeout}ms",
37
50
  scheduler_apiExecutionFailed: "API call failed: {error}",
51
+ scheduler_apiResponseTooLarge: "API response exceeds the {maxResponseBytes} byte limit",
38
52
  scheduler_dbSaveFailed: "Failed to save execution log: {error}",
39
53
  scheduler_dbNotInitialized: "Database not initialized, cannot save execution logs",
40
54
  scheduler_configError: "Scheduler config validation failed: {error}",
41
55
  scheduler_taskIdEmpty: "Task ID cannot be empty",
56
+ scheduler_invalidPersistedTask: "Invalid persisted task {taskId}: {error}",
42
57
  scheduler_taskRunning: "Task is currently running: {taskId}",
43
58
  scheduler_invalidApiConfig: "Invalid api_config for task: {taskId}",
44
- scheduler_lockAcquireFailed: "Failed to acquire distributed lock, another node already holds it: {taskId}",
45
59
  scheduler_jsCompileFailed: "Failed to compile JS task: {error}",
46
60
  scheduler_hookExecutionFailed: "Task lifecycle hook execution failed: {error}",
47
61
  scheduler_taskHandlerMissing: "Task has no executable handler and no global execute hook is configured: {taskId}",
48
62
  scheduler_invalidHandlerConfig: "Invalid task handler config: {taskId}",
49
63
  scheduler_invalidRetryConfig: "Invalid retry policy config for task: {taskId}",
50
- scheduler_reldbNotInitialized: "enableDb is true but @h-ai/reldb is not initialized, please call reldb.init() first"
64
+ scheduler_reldbNotInitialized: "enableDb is true but @h-ai/reldb is not initialized, please call reldb.init() first",
65
+ scheduler_executionUnknown: "Execution outcome is unknown; stop the old runner and verify external effects before resolving",
66
+ scheduler_executionStateFailed: "Shared execution state unavailable or owner lease lost",
67
+ scheduler_executionInputInvalid: "Invalid execution identifier or administration input",
68
+ scheduler_occurrenceHandled: "Occurrence already handled for task: {taskId}",
69
+ scheduler_logPersistFailed: "Execution log persistence is not confirmed. Repair it by receipt without rerunning the business task"
70
+ };
71
+
72
+ // messages/ja-JP.json
73
+ var ja_JP_default = {
74
+ $schema: "https://inlang.com/schema/inlang-message-format",
75
+ scheduler_notInitialized: "\u30B9\u30B1\u30B8\u30E5\u30FC\u30E9\u30FC\u304C\u521D\u671F\u5316\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u5148\u306Bscheduler.init()\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044",
76
+ scheduler_initFailed: "\u30B9\u30B1\u30B8\u30E5\u30FC\u30E9\u30FC\u306E\u521D\u671F\u5316\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
77
+ scheduler_alreadyRunning: "\u30B9\u30B1\u30B8\u30E5\u30FC\u30E9\u30FC\u306F\u65E2\u306B\u5B9F\u884C\u4E2D\u3067\u3059",
78
+ scheduler_notRunning: "\u30B9\u30B1\u30B8\u30E5\u30FC\u30E9\u30FC\u304C\u5B9F\u884C\u3055\u308C\u3066\u3044\u307E\u305B\u3093",
79
+ scheduler_closing: "\u30B9\u30B1\u30B8\u30E5\u30FC\u30E9\u30FC\u3092\u7D42\u4E86\u3057\u3066\u3044\u307E\u3059\u3002\u30BF\u30B9\u30AF\u306E\u5B9F\u884C\u3092\u30AD\u30E3\u30F3\u30BB\u30EB\u3057\u307E\u3057\u305F",
80
+ scheduler_definitionsChanged: "\u66F4\u65B0\u4E2D\u306B\u30BF\u30B9\u30AF\u5B9A\u7FA9\u304C\u5909\u66F4\u3055\u308C\u307E\u3057\u305F\u3002\u64CD\u4F5C\u3092\u518D\u8A66\u884C\u3057\u3066\u304F\u3060\u3055\u3044",
81
+ scheduler_taskNoLongerDue: "\u30BF\u30B9\u30AF{taskId}\u304C\u524A\u9664\u3001\u7121\u52B9\u5316\u3001\u307E\u305F\u306F\u518D\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\u3055\u308C\u307E\u3057\u305F",
82
+ scheduler_taskNotFound: "\u30BF\u30B9\u30AF\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093: {taskId}",
83
+ scheduler_taskAlreadyExists: "\u30BF\u30B9\u30AF\u306F\u65E2\u306B\u5B58\u5728\u3057\u307E\u3059: {taskId}",
84
+ scheduler_invalidCron: "cron\u5F0F\u304C\u7121\u52B9\u3067\u3059: {expression}",
85
+ scheduler_executionFailed: "\u30BF\u30B9\u30AF\u306E\u5B9F\u884C\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
86
+ scheduler_jsExecutionFailed: "JS\u30B3\u30FC\u30C9\u306E\u5B9F\u884C\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
87
+ scheduler_jsTimedOut: "JS\u30BF\u30B9\u30AF\u304C{timeout}ms\u3067\u30BF\u30A4\u30E0\u30A2\u30A6\u30C8\u3057\u307E\u3057\u305F",
88
+ scheduler_apiExecutionFailed: "API\u547C\u3073\u51FA\u3057\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
89
+ scheduler_apiResponseTooLarge: "API\u30EC\u30B9\u30DD\u30F3\u30B9\u304C{maxResponseBytes}\u30D0\u30A4\u30C8\u306E\u5236\u9650\u3092\u8D85\u3048\u3066\u3044\u307E\u3059",
90
+ scheduler_dbSaveFailed: "\u5B9F\u884C\u30ED\u30B0\u306E\u4FDD\u5B58\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
91
+ scheduler_dbNotInitialized: "\u30C7\u30FC\u30BF\u30D9\u30FC\u30B9\u304C\u521D\u671F\u5316\u3055\u308C\u3066\u3044\u306A\u3044\u305F\u3081\u3001\u5B9F\u884C\u30ED\u30B0\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093",
92
+ scheduler_configError: "\u30B9\u30B1\u30B8\u30E5\u30FC\u30E9\u30FC\u8A2D\u5B9A\u306E\u691C\u8A3C\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
93
+ scheduler_taskIdEmpty: "\u30BF\u30B9\u30AFID\u3092\u7A7A\u306B\u3059\u308B\u3053\u3068\u306F\u3067\u304D\u307E\u305B\u3093",
94
+ scheduler_invalidPersistedTask: "\u4FDD\u5B58\u3055\u308C\u305F\u30BF\u30B9\u30AF{taskId}\u304C\u7121\u52B9\u3067\u3059: {error}",
95
+ scheduler_taskRunning: "\u30BF\u30B9\u30AF\u306F\u73FE\u5728\u5B9F\u884C\u4E2D\u3067\u3059: {taskId}",
96
+ scheduler_invalidApiConfig: "\u30BF\u30B9\u30AF\u306Eapi_config\u304C\u7121\u52B9\u3067\u3059: {taskId}",
97
+ scheduler_jsCompileFailed: "JS\u30BF\u30B9\u30AF\u306E\u30B3\u30F3\u30D1\u30A4\u30EB\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
98
+ scheduler_hookExecutionFailed: "\u30BF\u30B9\u30AF\u306E\u30E9\u30A4\u30D5\u30B5\u30A4\u30AF\u30EB\u30D5\u30C3\u30AF\u306E\u5B9F\u884C\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {error}",
99
+ scheduler_taskHandlerMissing: "\u5B9F\u884C\u53EF\u80FD\u306A\u30CF\u30F3\u30C9\u30E9\u30FC\u3082\u30B0\u30ED\u30FC\u30D0\u30EBexecute\u30D5\u30C3\u30AF\u3082\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093: {taskId}",
100
+ scheduler_invalidHandlerConfig: "\u30BF\u30B9\u30AF\u30CF\u30F3\u30C9\u30E9\u30FC\u306E\u8A2D\u5B9A\u304C\u7121\u52B9\u3067\u3059: {taskId}",
101
+ scheduler_invalidRetryConfig: "\u30BF\u30B9\u30AF\u306E\u518D\u8A66\u884C\u30DD\u30EA\u30B7\u30FC\u306E\u8A2D\u5B9A\u304C\u7121\u52B9\u3067\u3059: {taskId}",
102
+ scheduler_reldbNotInitialized: "enableDb\u306Ftrue\u3067\u3059\u304C\u3001@h-ai/reldb\u304C\u521D\u671F\u5316\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002\u5148\u306Breldb.init()\u3092\u547C\u3073\u51FA\u3057\u3066\u304F\u3060\u3055\u3044",
103
+ scheduler_executionUnknown: "\u5B9F\u884C\u7D50\u679C\u306F\u4E0D\u660E\u3067\u3059\u3002\u624B\u52D5\u89E3\u6C7A\u3059\u308B\u524D\u306B\u53E4\u3044\u5B9F\u884C\u30D7\u30ED\u30BB\u30B9\u3092\u505C\u6B62\u3057\u3001\u5916\u90E8\u3078\u306E\u5F71\u97FF\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044",
104
+ scheduler_executionStateFailed: "\u5171\u6709\u5B9F\u884C\u72B6\u614B\u3092\u5229\u7528\u3067\u304D\u306A\u3044\u304B\u3001\u6240\u6709\u8005\u30EA\u30FC\u30B9\u304C\u5931\u308F\u308C\u307E\u3057\u305F",
105
+ scheduler_executionInputInvalid: "\u5B9F\u884C\u8B58\u5225\u5B50\u307E\u305F\u306F\u7BA1\u7406\u64CD\u4F5C\u306E\u5165\u529B\u304C\u7121\u52B9\u3067\u3059",
106
+ scheduler_occurrenceHandled: "\u30BF\u30B9\u30AF {taskId} \u306E\u4ECA\u56DE\u306E\u30B9\u30B1\u30B8\u30E5\u30FC\u30EB\u306F\u65E2\u306B\u51E6\u7406\u6E08\u307F\u3067\u3059",
107
+ scheduler_logPersistFailed: "\u5B9F\u884C\u30ED\u30B0\u306E\u6C38\u7D9A\u5316\u306F\u672A\u78BA\u8A8D\u3067\u3059\u3002\u53D7\u9818\u8A18\u9332\u306B\u57FA\u3065\u3044\u3066\u30ED\u30B0\u3092\u88DC\u5B8C\u3057\u3001\u696D\u52D9\u30BF\u30B9\u30AF\u3092\u518D\u5B9F\u884C\u3057\u306A\u3044\u3067\u304F\u3060\u3055\u3044"
51
108
  };
52
109
 
53
110
  // messages/zh-CN.json
@@ -57,31 +114,42 @@ var zh_CN_default = {
57
114
  scheduler_initFailed: "\u5B9A\u65F6\u4EFB\u52A1\u6A21\u5757\u521D\u59CB\u5316\u5931\u8D25: {error}",
58
115
  scheduler_alreadyRunning: "\u5B9A\u65F6\u4EFB\u52A1\u8C03\u5EA6\u5668\u5DF2\u5728\u8FD0\u884C\u4E2D",
59
116
  scheduler_notRunning: "\u5B9A\u65F6\u4EFB\u52A1\u8C03\u5EA6\u5668\u672A\u8FD0\u884C",
117
+ scheduler_closing: "\u8C03\u5EA6\u5668\u6B63\u5728\u5173\u95ED\uFF0C\u4EFB\u52A1\u6267\u884C\u5DF2\u53D6\u6D88",
118
+ scheduler_definitionsChanged: "\u5237\u65B0\u671F\u95F4\u4EFB\u52A1\u5B9A\u4E49\u5DF2\u53D8\u5316\uFF0C\u8BF7\u91CD\u8BD5\u64CD\u4F5C",
119
+ scheduler_taskNoLongerDue: "\u4EFB\u52A1 {taskId} \u5DF2\u5220\u9664\u3001\u7981\u7528\u6216\u6539\u53D8\u8C03\u5EA6\u65F6\u95F4",
60
120
  scheduler_taskNotFound: "\u4EFB\u52A1\u672A\u627E\u5230: {taskId}",
61
121
  scheduler_taskAlreadyExists: "\u4EFB\u52A1\u5DF2\u5B58\u5728: {taskId}",
62
122
  scheduler_invalidCron: "\u65E0\u6548\u7684 cron \u8868\u8FBE\u5F0F: {expression}",
63
123
  scheduler_executionFailed: "\u4EFB\u52A1\u6267\u884C\u5931\u8D25: {error}",
64
124
  scheduler_jsExecutionFailed: "JS \u4EE3\u7801\u6267\u884C\u5931\u8D25: {error}",
125
+ scheduler_jsTimedOut: "JS \u4EFB\u52A1\u6267\u884C\u8D85\u8FC7 {timeout} \u6BEB\u79D2",
65
126
  scheduler_apiExecutionFailed: "API \u8C03\u7528\u5931\u8D25: {error}",
127
+ scheduler_apiResponseTooLarge: "API \u54CD\u5E94\u8D85\u8FC7 {maxResponseBytes} \u5B57\u8282\u4E0A\u9650",
66
128
  scheduler_dbSaveFailed: "\u4FDD\u5B58\u6267\u884C\u8BB0\u5F55\u5931\u8D25: {error}",
67
129
  scheduler_dbNotInitialized: "\u6570\u636E\u5E93\u672A\u521D\u59CB\u5316\uFF0C\u65E0\u6CD5\u4FDD\u5B58\u6267\u884C\u8BB0\u5F55",
68
130
  scheduler_configError: "\u8C03\u5EA6\u5668\u914D\u7F6E\u6821\u9A8C\u5931\u8D25\uFF1A{error}",
69
131
  scheduler_taskIdEmpty: "\u4EFB\u52A1 ID \u4E0D\u80FD\u4E3A\u7A7A",
132
+ scheduler_invalidPersistedTask: "\u6301\u4E45\u5316\u4EFB\u52A1 {taskId} \u65E0\u6548\uFF1A{error}",
70
133
  scheduler_taskRunning: "\u4EFB\u52A1\u6B63\u5728\u6267\u884C\u4E2D: {taskId}",
71
134
  scheduler_invalidApiConfig: "\u4EFB\u52A1 api_config \u683C\u5F0F\u65E0\u6548: {taskId}",
72
- scheduler_lockAcquireFailed: "\u83B7\u53D6\u5206\u5E03\u5F0F\u9501\u5931\u8D25\uFF0C\u5176\u4ED6\u8282\u70B9\u5DF2\u83B7\u9501: {taskId}",
73
135
  scheduler_jsCompileFailed: "JS \u4EFB\u52A1\u7F16\u8BD1\u5931\u8D25: {error}",
74
136
  scheduler_hookExecutionFailed: "\u4EFB\u52A1\u751F\u547D\u5468\u671F\u56DE\u8C03\u6267\u884C\u5931\u8D25: {error}",
75
137
  scheduler_taskHandlerMissing: "\u4EFB\u52A1\u7F3A\u5C11\u53EF\u6267\u884C handler\uFF0C\u4E14\u672A\u914D\u7F6E\u5168\u5C40\u6267\u884C\u56DE\u8C03: {taskId}",
76
138
  scheduler_invalidHandlerConfig: "\u4EFB\u52A1 handler \u914D\u7F6E\u65E0\u6548: {taskId}",
77
139
  scheduler_invalidRetryConfig: "\u4EFB\u52A1\u91CD\u8BD5\u7B56\u7565\u914D\u7F6E\u65E0\u6548: {taskId}",
78
- scheduler_reldbNotInitialized: "enableDb \u4E3A true \u4F46 @h-ai/reldb \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 reldb.init()"
140
+ scheduler_reldbNotInitialized: "enableDb \u4E3A true \u4F46 @h-ai/reldb \u672A\u521D\u59CB\u5316\uFF0C\u8BF7\u5148\u8C03\u7528 reldb.init()",
141
+ scheduler_executionUnknown: "\u6267\u884C\u7ED3\u679C\u672A\u77E5\uFF1B\u8BF7\u5148\u7EC8\u6B62\u65E7 runner \u5E76\u6838\u5BF9\u5916\u90E8\u526F\u4F5C\u7528\u540E\u88C1\u5B9A",
142
+ scheduler_executionStateFailed: "\u5171\u4EAB\u6267\u884C\u72B6\u6001\u4E0D\u53EF\u7528\u6216 owner \u79DF\u7EA6\u5DF2\u5931\u6548",
143
+ scheduler_executionInputInvalid: "\u6267\u884C\u6807\u8BC6\u6216\u8FD0\u7EF4\u8F93\u5165\u4E0D\u5408\u6CD5",
144
+ scheduler_occurrenceHandled: "\u672C\u6B21\u8C03\u5EA6\u5DF2\u5904\u7406: {taskId}",
145
+ scheduler_logPersistFailed: "\u6267\u884C\u65E5\u5FD7\u5C1A\u672A\u786E\u8BA4\u6301\u4E45\u5316\uFF0C\u8BF7\u6309\u6267\u884C\u56DE\u6267\u8865\u5199\uFF1B\u4E0D\u8981\u91CD\u65B0\u6267\u884C\u4E1A\u52A1"
79
146
  };
80
147
 
81
148
  // src/scheduler-i18n.ts
82
149
  var schedulerM = core.i18n.createMessageGetter({
83
150
  "zh-CN": zh_CN_default,
84
- "en-US": en_US_default
151
+ "en-US": en_US_default,
152
+ "ja-JP": ja_JP_default
85
153
  });
86
154
  var SchedulerErrorInfo = {
87
155
  NOT_INITIALIZED: "010:500",
@@ -96,13 +164,264 @@ var SchedulerErrorInfo = {
96
164
  DB_SAVE_FAILED: "026:500",
97
165
  ALREADY_RUNNING: "027:409",
98
166
  NOT_RUNNING: "028:400",
99
- LOCK_ACQUIRE_FAILED: "029:409",
100
167
  JS_COMPILE_FAILED: "030:500",
101
- HOOK_EXECUTION_FAILED: "031:500"
168
+ HOOK_EXECUTION_FAILED: "031:500",
169
+ LOG_PERSIST_FAILED: "032:500"
102
170
  };
103
171
  var HaiSchedulerError = core.error.buildHaiErrorsDef("scheduler", SchedulerErrorInfo);
104
172
 
105
- // src/repositories/scheduler-log-repository.ts
173
+ // src/repositories/scheduler-repository-execution.ts
174
+ var TABLE = "hai_scheduler_executions";
175
+ function executionId(taskId, type, key) {
176
+ return createHash("sha256").update(JSON.stringify([taskId, type, key])).digest("hex");
177
+ }
178
+ function executionEntry(row) {
179
+ return { occurrenceId: row.occurrenceId, taskId: row.taskId, status: row.status, sequence: row.sequence, attemptCount: row.attemptCount, updatedAt: row.updatedAt, logPersistence: row.logPersistence };
180
+ }
181
+ function failed(cause) {
182
+ return err(HaiSchedulerError.DB_SAVE_FAILED, schedulerM("scheduler_executionStateFailed"), cause);
183
+ }
184
+ var SchedulerExecutionRepository = class extends BaseReldbCrudRepository {
185
+ constructor(db) {
186
+ super(db, {
187
+ table: TABLE,
188
+ idColumn: "sequence",
189
+ idField: "sequence",
190
+ fields: [
191
+ { fieldName: "sequence", columnName: "sequence", def: { type: "INTEGER", primaryKey: true, autoIncrement: true }, select: true, create: false, update: false },
192
+ ...[
193
+ ["occurrenceId", "occurrence_id", true, true],
194
+ ["taskId", "task_id", true, false],
195
+ ["activeTask", "active_task", false, true],
196
+ ["status", "status", true, false],
197
+ ["owner", "owner", false, false],
198
+ ["snapshot", "snapshot", true, false],
199
+ ["triggerJson", "trigger_json", true, false],
200
+ ["logJson", "log_json", false, false],
201
+ ["logsJson", "logs_json", false, false],
202
+ ["logPersistence", "log_persistence", true, false]
203
+ ].map(([fieldName, columnName, notNull, unique]) => ({
204
+ fieldName: String(fieldName),
205
+ columnName: String(columnName),
206
+ def: { type: ["snapshot", "triggerJson", "logJson", "logsJson"].includes(String(fieldName)) ? "JSON" : "TEXT", notNull: Boolean(notNull), unique: Boolean(unique) },
207
+ select: true,
208
+ create: true,
209
+ update: true
210
+ })),
211
+ ...[
212
+ ["leasedUntil", "leased_until"],
213
+ ["attemptCount", "attempt_count"],
214
+ ["maxAttempts", "max_attempts"],
215
+ ["updatedAt", "updated_at"],
216
+ ["createdAt", "created_at"]
217
+ ].map(([fieldName, columnName]) => ({
218
+ fieldName,
219
+ columnName,
220
+ def: { type: "BIGINT", notNull: true },
221
+ select: true,
222
+ create: true,
223
+ update: true
224
+ })),
225
+ { fieldName: "idempotent", columnName: "idempotent", def: { type: "BOOLEAN", notNull: true }, select: true, create: true, update: true }
226
+ ]
227
+ });
228
+ }
229
+ /**
230
+ * 只按已初始化的数据库类型选择存储端毫秒时钟。
231
+ * PostgreSQL/MySQL 使用执行时钟,不能使用固定在事务/语句开始处的时间快照。
232
+ * 期限表达式直接进入有 owner 条件的 SQL;先 SELECT 时间再写入仍有等待窗口。
233
+ *
234
+ * @example
235
+ * ```ts
236
+ * // 模块内部上下文:当前仓库实例仅生成固定白名单 SQL,不接收调用方表达式。
237
+ * const deadlinePredicate = `leased_until > ${this.databaseClock()}`
238
+ * ```
239
+ */
240
+ databaseClock() {
241
+ if (this.db.config?.type === "postgresql")
242
+ return "CAST(FLOOR(EXTRACT(EPOCH FROM clock_timestamp()) * 1000) AS BIGINT)";
243
+ if (this.db.config?.type === "mysql")
244
+ return "CAST(UNIX_TIMESTAMP(SYSDATE(3)) * 1000 AS UNSIGNED)";
245
+ return "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)";
246
+ }
247
+ /** 同毫秒内的持久状态版本仍单调增加,日志确认/人工裁定不依赖节点墙钟。 */
248
+ nextUpdatedAt() {
249
+ const clock = this.databaseClock();
250
+ return `CASE WHEN updated_at >= ${clock} THEN updated_at + 1 ELSE ${clock} END`;
251
+ }
252
+ /** 存储端毫秒时钟供 cron 计算共享分钟身份;读取失败停止本轮调度,不回退节点时钟。 */
253
+ async currentTime() {
254
+ const result = await this.db.sql.get(`SELECT ${this.databaseClock()} AS now`);
255
+ if (!result.success)
256
+ return failed(result.error);
257
+ const now = Number(result.data?.now);
258
+ return Number.isSafeInteger(now) && now >= 0 ? ok(now) : failed();
259
+ }
260
+ /** 读取统一校验 BIGINT,不能把 PG 字符串时间或舍入的序号用于 owner 判断。 */
261
+ normalize(row) {
262
+ const value = { ...row };
263
+ for (const field of ["snapshot", "triggerJson", "logJson", "logsJson"]) {
264
+ if (row[field] !== void 0 && row[field] !== null && typeof row[field] !== "string")
265
+ value[field] = JSON.stringify(row[field]);
266
+ }
267
+ for (const field of ["sequence", "leasedUntil", "attemptCount", "maxAttempts", "updatedAt", "createdAt"]) {
268
+ const number = Number(row[field]);
269
+ if (!Number.isSafeInteger(number) || number < 0)
270
+ return failed();
271
+ value[field] = number;
272
+ }
273
+ return ok(value);
274
+ }
275
+ /** 按稳定回执读取。@example await repository.byOccurrence(id) */
276
+ async byOccurrence(id) {
277
+ const rows = await this.findAll({ where: "occurrence_id = ?", params: [id], limit: 1 });
278
+ if (!rows.success)
279
+ return failed(rows.error);
280
+ return rows.data[0] ? this.normalize(rows.data[0]) : ok(null);
281
+ }
282
+ /** 有界读取过期执行,跨分钟恢复原 occurrence,而不是创建新的副作用身份。@example await repository.expired() */
283
+ async expired() {
284
+ return this.rows(`status IN (?, ?) AND leased_until <= ${this.databaseClock()}`, ["claimed", "running"], 100, 0);
285
+ }
286
+ /** 任务被删除或触发元数据损坏时,过期记录隔离为 unknown,允许可信人工核对而非永久悬挂。 */
287
+ async isolateExpired(row) {
288
+ const result = await this.db.sql.execute(
289
+ `UPDATE ${TABLE} SET status = ?, owner = NULL, leased_until = 0, updated_at = ${this.nextUpdatedAt()}
290
+ WHERE occurrence_id = ? AND owner = ? AND leased_until <= ${this.databaseClock()} AND status IN (?, ?)`,
291
+ ["unknown", row.occurrenceId, row.owner, "claimed", "running"]
292
+ );
293
+ return result.success && result.data.changes === 1 ? ok(void 0) : failed();
294
+ }
295
+ /** 有界读取待人工核对记录。@example await repository.unknown(50, 0) */
296
+ async unknown(limit, offset) {
297
+ return this.rows("status = ?", ["unknown"], limit, offset);
298
+ }
299
+ /** 仅查询已发布终态且日志待补写的回执。@example await repository.pendingLogs(50, 0) */
300
+ async pendingLogs(limit, offset) {
301
+ return this.rows("log_persistence = ? AND status NOT IN (?, ?)", ["pending", "claimed", "running"], limit, offset);
302
+ }
303
+ /**
304
+ * 确认相同终态快照的日志投影;不变更业务状态,不重新领取任务。
305
+ * @example await repository.confirmLogs(row)
306
+ */
307
+ async confirmLogs(row) {
308
+ if (!row.logJson || !row.logsJson)
309
+ return failed();
310
+ const log = JSON.parse(row.logJson);
311
+ const result = await this.db.sql.execute(
312
+ `UPDATE ${TABLE} SET log_persistence = ?, log_json = ?, updated_at = ${this.nextUpdatedAt()}
313
+ WHERE occurrence_id = ? AND updated_at = ? AND log_persistence = ? AND status NOT IN (?, ?)`,
314
+ ["persisted", JSON.stringify({ ...log, persistence: { status: "persisted" } }), row.occurrenceId, row.updatedAt, "pending", "claimed", "running"]
315
+ );
316
+ if (result.success && result.data.changes === 1)
317
+ return ok(void 0);
318
+ const current = await this.byOccurrence(row.occurrenceId);
319
+ return current.success && current.data?.logPersistence === "persisted" && current.data.logsJson === row.logsJson ? ok(void 0) : failed();
320
+ }
321
+ async rows(where, params, limit, offset) {
322
+ const result = await this.findAll({ where, params, limit, offset, orderBy: "sequence ASC" });
323
+ if (!result.success)
324
+ return failed(result.error);
325
+ const rows = [];
326
+ for (const row of result.data) {
327
+ const normalized = this.normalize(row);
328
+ if (!normalized.success)
329
+ return normalized;
330
+ rows.push(normalized.data);
331
+ }
332
+ return ok(rows);
333
+ }
334
+ /**
335
+ * 唯一 active_task 防止不同 occurrence 并行;同 occurrence 只可恢复安全的过期记录。
336
+ * @example await repository.claim(task, id, trigger, nodeId, leaseMs)
337
+ */
338
+ async claim(task, id, trigger, nodeId, leaseMs) {
339
+ const ready = await this.ensureReady();
340
+ if (!ready.success)
341
+ return failed(ready.error);
342
+ const clock = this.databaseClock();
343
+ const owner = `${nodeId}:${randomUUID()}`;
344
+ let created;
345
+ try {
346
+ created = await this.db.sql.execute(
347
+ `INSERT INTO ${TABLE} (occurrence_id, task_id, active_task, status, owner, leased_until, attempt_count, max_attempts, idempotent, snapshot, trigger_json, log_persistence, updated_at, created_at)
348
+ VALUES (?, ?, ?, ?, ?, ${clock} + ?, 0, ?, ?, ?, ?, ?, ${clock}, ${clock})`,
349
+ [id, task.id, task.id, "claimed", owner, leaseMs, task.retry?.maxAttempts ?? 1, this.db.config?.type === "postgresql" ? task.idempotent === true : Number(task.idempotent === true), JSON.stringify(task), JSON.stringify(trigger), "unconfirmed"]
350
+ );
351
+ } catch (cause) {
352
+ return failed(cause);
353
+ }
354
+ const existing = await this.byOccurrence(id);
355
+ if (!existing.success)
356
+ return existing;
357
+ if (!existing.data) {
358
+ const active = await this.findAll({ where: "active_task = ?", params: [task.id], limit: 1 });
359
+ return active.success && active.data.length > 0 ? ok(null) : failed(created.success ? void 0 : created.error);
360
+ }
361
+ const row = existing.data;
362
+ if (created.success || ["success", "failed", "interrupted", "discarded"].includes(row.status))
363
+ return ok(row);
364
+ if (row.status === "unknown")
365
+ return ok(null);
366
+ if (row.status === "running" && (!row.idempotent || row.attemptCount >= row.maxAttempts)) {
367
+ const isolated = await this.db.sql.execute(
368
+ `UPDATE ${TABLE} SET status = ?, owner = NULL, leased_until = 0, updated_at = ${this.nextUpdatedAt()}
369
+ WHERE occurrence_id = ? AND owner = ? AND leased_until <= ${clock} AND status = ?`,
370
+ ["unknown", id, row.owner, "running"]
371
+ );
372
+ return isolated.success ? ok(null) : failed(isolated.error);
373
+ }
374
+ const recovered = await this.db.sql.execute(
375
+ `UPDATE ${TABLE} SET status = ?, owner = ?, leased_until = ${clock} + ?, updated_at = ${this.nextUpdatedAt()}
376
+ WHERE occurrence_id = ? AND owner = ? AND leased_until <= ${clock} AND status IN (?, ?)`,
377
+ ["claimed", owner, leaseMs, id, row.owner, "claimed", "running"]
378
+ );
379
+ if (!recovered.success)
380
+ return failed(recovered.error);
381
+ return recovered.data.changes === 1 ? this.byOccurrence(id) : ok(null);
382
+ }
383
+ /** 外部副作用前的条件门闩,并原子递增持久尝试次数。@example await repository.begin(row, leaseMs) */
384
+ async begin(row, leaseMs) {
385
+ const clock = this.databaseClock();
386
+ const result = await this.db.sql.execute(
387
+ `UPDATE ${TABLE} SET status = ?, attempt_count = attempt_count + 1, leased_until = ${clock} + ?, updated_at = ${this.nextUpdatedAt()}
388
+ WHERE occurrence_id = ? AND owner = ? AND leased_until > ${clock} AND status IN (?, ?) AND attempt_count < max_attempts`,
389
+ ["running", leaseMs, row.occurrenceId, row.owner, "claimed", "running"]
390
+ );
391
+ if (!result.success || result.data.changes !== 1)
392
+ return failed(result.success ? void 0 : result.error);
393
+ row.status = "running";
394
+ row.attemptCount += 1;
395
+ return ok(void 0);
396
+ }
397
+ /** 只续租仍然有效的 owner;过期凭据不能复活。@example await repository.renew(row, leaseMs) */
398
+ async renew(row, leaseMs) {
399
+ const clock = this.databaseClock();
400
+ const result = await this.db.sql.execute(
401
+ `UPDATE ${TABLE} SET leased_until = ${clock} + ?, updated_at = ${this.nextUpdatedAt()} WHERE occurrence_id = ? AND owner = ? AND leased_until > ${clock} AND status IN (?, ?)`,
402
+ [leaseMs, row.occurrenceId, row.owner, "claimed", "running"]
403
+ );
404
+ return result.success && result.data.changes === 1 ? ok(void 0) : failed();
405
+ }
406
+ /** 有效 owner 确认终态;unknown 保留串行槽,阻止下一 cron/manual 与旧副作用并行。@example await repository.finish(row, log) */
407
+ async finish(row, log, logs = [log]) {
408
+ const clock = this.databaseClock();
409
+ const result = await this.db.sql.execute(
410
+ `UPDATE ${TABLE} SET status = ?, active_task = ?, owner = NULL, leased_until = 0, log_json = ?, logs_json = ?, log_persistence = ?, updated_at = ${this.nextUpdatedAt()}
411
+ WHERE occurrence_id = ? AND owner = ? AND leased_until > ${clock} AND status IN (?, ?)`,
412
+ [log.status, log.status === "unknown" ? row.taskId : null, JSON.stringify(log), JSON.stringify(logs), "pending", row.occurrenceId, row.owner, "claimed", "running"]
413
+ );
414
+ return result.success && result.data.changes === 1 ? ok(void 0) : failed();
415
+ }
416
+ /** 人工隔离旧 runner 后条件裁定;不重排旧 occurrence,只有成功裁定才释放任务槽。@example await repository.resolve(id, 'discarded', updatedAt) */
417
+ async resolve(id, status, expectedUpdatedAt) {
418
+ const result = await this.db.sql.execute(
419
+ `UPDATE ${TABLE} SET status = ?, active_task = NULL, updated_at = ${this.nextUpdatedAt()} WHERE occurrence_id = ? AND status = ? AND updated_at = ?`,
420
+ [status, id, "unknown", expectedUpdatedAt]
421
+ );
422
+ return result.success && result.data.changes === 1 ? ok(void 0) : failed();
423
+ }
424
+ };
106
425
  var logger = core.logger.child({ module: "scheduler", scope: "log-repository" });
107
426
  var SCHEDULER_LOG_TABLE = "hai_scheduler_logs";
108
427
  var SchedulerLogRepository = class extends BaseReldbCrudRepository {
@@ -111,41 +430,53 @@ var SchedulerLogRepository = class extends BaseReldbCrudRepository {
111
430
  table: SCHEDULER_LOG_TABLE,
112
431
  idColumn: "id",
113
432
  fields: [
114
- { fieldName: "id", columnName: "id", def: { type: "INTEGER", primaryKey: true, autoIncrement: true }, select: true, create: false, update: false },
433
+ { fieldName: "id", columnName: "id", def: { type: "TEXT", primaryKey: true }, select: true, create: true, update: false },
434
+ { fieldName: "occurrenceId", columnName: "occurrence_id", def: { type: "TEXT" }, select: true, create: true, update: false },
115
435
  { fieldName: "taskId", columnName: "task_id", def: { type: "TEXT", notNull: true }, select: true, create: true, update: false },
116
436
  { fieldName: "taskName", columnName: "task_name", def: { type: "TEXT", notNull: true }, select: true, create: true, update: false },
117
437
  { fieldName: "taskType", columnName: "task_type", def: { type: "TEXT", notNull: true }, select: true, create: true, update: false },
118
438
  { fieldName: "triggerType", columnName: "trigger_type", def: { type: "TEXT", notNull: true }, select: true, create: true, update: false },
119
439
  { fieldName: "triggerSource", columnName: "trigger_source", def: { type: "TEXT" }, select: true, create: true, update: false },
120
440
  { fieldName: "status", columnName: "status", def: { type: "TEXT", notNull: true }, select: true, create: true, update: false },
121
- { fieldName: "result", columnName: "result", def: { type: "TEXT" }, select: true, create: true, update: false },
122
- { fieldName: "error", columnName: "error", def: { type: "TEXT" }, select: true, create: true, update: false },
123
- { fieldName: "startedAt", columnName: "started_at", def: { type: "INTEGER", notNull: true }, select: true, create: true, update: false },
124
- { fieldName: "finishedAt", columnName: "finished_at", def: { type: "INTEGER", notNull: true }, select: true, create: true, update: false },
441
+ { fieldName: "payload", columnName: "payload", def: { type: "JSON", notNull: true }, select: true, create: true, update: false },
442
+ { fieldName: "startedAt", columnName: "started_at", def: { type: "BIGINT", notNull: true }, select: true, create: true, update: false },
443
+ { fieldName: "finishedAt", columnName: "finished_at", def: { type: "BIGINT", notNull: true }, select: true, create: true, update: false },
125
444
  { fieldName: "duration", columnName: "duration", def: { type: "INTEGER", notNull: true }, select: true, create: true, update: false }
126
445
  ]
127
446
  });
128
447
  }
448
+ /**
449
+ * 按固定 UUID 写入完整日志;写入失败后重读相同主键,只有真实内容相同才视为已保存。
450
+ * @example `const saved = await repository.saveLog(log); if (!saved.success) return saved`
451
+ */
129
452
  async saveLog(log) {
453
+ const payload = { ...log, persistence: { status: "persisted" } };
130
454
  try {
131
- const createResult = await this.create({
455
+ const created = await this.create({
456
+ id: log.id,
457
+ occurrenceId: log.occurrenceId,
132
458
  taskId: log.taskId,
133
459
  taskName: log.taskName,
134
460
  taskType: log.taskType,
135
461
  triggerType: log.triggerType,
136
462
  triggerSource: log.triggerSource,
137
463
  status: log.status,
138
- result: log.result,
139
- error: log.error,
464
+ payload,
140
465
  startedAt: log.startedAt,
141
466
  finishedAt: log.finishedAt,
142
467
  duration: log.duration
143
468
  });
144
- if (!createResult.success)
145
- logger.error("Failed to save execution log", { taskId: log.taskId, error: createResult.error.message });
146
- } catch (error) {
147
- logger.error("Failed to save execution log", { taskId: log.taskId, error });
469
+ if (created.success)
470
+ return ok(void 0);
471
+ } catch {
472
+ }
473
+ try {
474
+ const existing = await this.findById(log.id);
475
+ if (existing.success && existing.data && isDeepStrictEqual(existing.data.payload, payload))
476
+ return ok(void 0);
477
+ } catch {
148
478
  }
479
+ return err(HaiSchedulerError.LOG_PERSIST_FAILED, schedulerM("scheduler_logPersistFailed"));
149
480
  }
150
481
  async queryLogs(options) {
151
482
  const { taskId, status, triggerType, triggerSource, startedAfter, startedBefore, pagination } = options ?? {};
@@ -179,7 +510,7 @@ var SchedulerLogRepository = class extends BaseReldbCrudRepository {
179
510
  const pageResult = await this.findPage({
180
511
  where: conditions.length > 0 ? conditions.join(" AND ") : void 0,
181
512
  params: params.length > 0 ? params : void 0,
182
- orderBy: "id DESC",
513
+ orderBy: "started_at DESC, id DESC",
183
514
  pagination,
184
515
  overrides: { defaultPageSize: 20, maxPageSize: 200 }
185
516
  });
@@ -192,20 +523,7 @@ var SchedulerLogRepository = class extends BaseReldbCrudRepository {
192
523
  }
193
524
  return ok({
194
525
  ...pageResult.data,
195
- items: pageResult.data.items.map((row) => ({
196
- id: row.id,
197
- taskId: row.taskId,
198
- taskName: row.taskName,
199
- taskType: row.taskType,
200
- triggerType: row.triggerType,
201
- triggerSource: row.triggerSource ?? null,
202
- status: row.status,
203
- result: row.result ?? null,
204
- error: row.error ?? null,
205
- startedAt: row.startedAt,
206
- finishedAt: row.finishedAt,
207
- duration: row.duration
208
- }))
526
+ items: pageResult.data.items.map((row) => ({ ...row.payload, persistence: { status: "persisted" } }))
209
527
  });
210
528
  } catch (error) {
211
529
  logger.error("Failed to query execution logs", { error });
@@ -275,7 +593,7 @@ var logger2 = core.logger.child({ module: "scheduler", scope: "task-repository"
275
593
  var SCHEDULER_TASK_TABLE = "hai_scheduler_tasks";
276
594
  var TaskParamsSchema = z.record(z.string(), z.unknown());
277
595
  var TaskRetryPolicySchema = z.object({
278
- maxAttempts: z.number().int().min(1),
596
+ maxAttempts: z.number().int().min(1).max(100),
279
597
  backoffMs: z.array(z.number().int().min(0)).optional()
280
598
  });
281
599
  var ApiTaskConfigSchema = z.object({
@@ -284,7 +602,8 @@ var ApiTaskConfigSchema = z.object({
284
602
  method: z.enum(["GET", "POST", "PUT", "DELETE", "PATCH"]).optional(),
285
603
  headers: z.record(z.string(), z.string()).optional(),
286
604
  body: z.unknown().optional(),
287
- timeout: z.number().int().positive().optional()
605
+ timeout: z.number().int().positive().optional(),
606
+ maxResponseBytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional()
288
607
  });
289
608
  var JsTaskConfigSchema = z.object({
290
609
  kind: z.literal("js"),
@@ -303,7 +622,9 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
303
622
  { fieldName: "taskName", columnName: "task_name", def: { type: "TEXT", notNull: true }, select: true, create: true, update: true },
304
623
  { fieldName: "description", columnName: "description", def: { type: "TEXT" }, select: true, create: true, update: true },
305
624
  { fieldName: "cron", columnName: "cron", def: { type: "TEXT", notNull: true }, select: true, create: true, update: true },
625
+ { fieldName: "timezone", columnName: "timezone", def: { type: "TEXT" }, select: true, create: true, update: true },
306
626
  { fieldName: "enabled", columnName: "enabled", def: { type: "BOOLEAN", notNull: true, defaultValue: true }, select: true, create: true, update: true },
627
+ { fieldName: "idempotent", columnName: "idempotent", def: { type: "BOOLEAN", notNull: true, defaultValue: false }, select: true, create: true, update: true },
307
628
  { fieldName: "deleteAfterRun", columnName: "delete_after_run", def: { type: "BOOLEAN", notNull: true, defaultValue: false }, select: true, create: true, update: true },
308
629
  { fieldName: "retry", columnName: "retry", def: { type: "JSON" }, select: true, create: true, update: true },
309
630
  { fieldName: "params", columnName: "params", def: { type: "JSON" }, select: true, create: true, update: true },
@@ -320,7 +641,9 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
320
641
  taskName: task.name,
321
642
  description: task.description ?? null,
322
643
  cron: task.cron,
644
+ timezone: task.timezone ?? null,
323
645
  enabled: task.enabled !== false,
646
+ idempotent: task.idempotent === true,
324
647
  deleteAfterRun: task.deleteAfterRun === true,
325
648
  retry: task.retry ?? null,
326
649
  params: task.params ?? {},
@@ -366,8 +689,12 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
366
689
  data.description = updates.description ?? null;
367
690
  if (updates.cron !== void 0)
368
691
  data.cron = updates.cron;
692
+ if (updates.timezone !== void 0)
693
+ data.timezone = updates.timezone ?? null;
369
694
  if (updates.enabled !== void 0)
370
695
  data.enabled = updates.enabled;
696
+ if (updates.idempotent !== void 0)
697
+ data.idempotent = updates.idempotent;
371
698
  if (updates.deleteAfterRun !== void 0)
372
699
  data.deleteAfterRun = updates.deleteAfterRun;
373
700
  if (updates.retry !== void 0)
@@ -400,8 +727,29 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
400
727
  );
401
728
  }
402
729
  }
403
- async deleteTask(taskId) {
730
+ /** 删除任务;自动清理携带执行定义,在同一条 DELETE 内原子比较,保留并发编辑。 */
731
+ async deleteTask(taskId, expected) {
404
732
  try {
733
+ if (expected) {
734
+ const conditions = ["task_id = ?", "task_name = ?", "cron = ?", "COALESCE(timezone, '') = ?", "COALESCE(description, '') = ?", "enabled = ?", "delete_after_run = ?", "idempotent = ?"];
735
+ const postgres = this.db.config?.type === "postgresql";
736
+ const enabled = expected.enabled !== false;
737
+ const deleteAfterRun = expected.deleteAfterRun === true;
738
+ const params = [taskId, expected.name, expected.cron, expected.timezone ?? "", expected.description ?? "", postgres ? enabled : Number(enabled), postgres ? deleteAfterRun : Number(deleteAfterRun), postgres ? expected.idempotent === true : Number(expected.idempotent === true)];
739
+ const jsonValue = this.db.config?.type === "mysql" ? "CAST(? AS JSON)" : this.db.config?.type === "postgresql" ? "CAST(? AS JSONB)" : "?";
740
+ const jsonFields = [["retry", expected.retry], ["params", expected.params ?? {}], ["handler", expected.handler]];
741
+ for (const [column, value] of jsonFields) {
742
+ if (value === void 0 || value === null) {
743
+ conditions.push(`(${column} IS NULL OR ${column} = ${jsonValue})`);
744
+ params.push("null");
745
+ } else {
746
+ conditions.push(`${column} = ${jsonValue}`);
747
+ params.push(JSON.stringify(value));
748
+ }
749
+ }
750
+ const deleted = await this.db.sql.execute(`DELETE FROM ${SCHEDULER_TASK_TABLE} WHERE ${conditions.join(" AND ")}`, params);
751
+ return deleted.success ? ok(deleted.data.changes > 0) : deleted;
752
+ }
405
753
  const rows = await this.findAll({ where: "task_id = ?", params: [taskId], limit: 1 });
406
754
  if (!rows.success) {
407
755
  return err(
@@ -411,7 +759,7 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
411
759
  );
412
760
  }
413
761
  if (rows.data.length === 0)
414
- return ok(void 0);
762
+ return ok(false);
415
763
  const deleteResult = await this.deleteById(rows.data[0].id);
416
764
  if (!deleteResult.success) {
417
765
  logger2.error("Failed to delete task definition", { taskId, error: deleteResult.error.message });
@@ -421,7 +769,7 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
421
769
  deleteResult.error
422
770
  );
423
771
  }
424
- return ok(void 0);
772
+ return ok(deleteResult.data.changes > 0);
425
773
  } catch (error) {
426
774
  logger2.error("Failed to delete task definition", { taskId, error });
427
775
  return err(
@@ -447,25 +795,24 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
447
795
  for (const row of rows.data) {
448
796
  const paramsResult = TaskParamsSchema.safeParse(row.params ?? {});
449
797
  if (!paramsResult.success) {
450
- logger2.warn("Skipping task with invalid params", { taskId: row.taskId, error: paramsResult.error.message });
451
- continue;
798
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_invalidPersistedTask", { params: { taskId: row.taskId, error: paramsResult.error.message } }));
452
799
  }
453
800
  const handlerResult = row.handler == null ? { success: true, data: void 0 } : TaskHandlerConfigSchema.safeParse(row.handler);
454
801
  if (!handlerResult.success) {
455
- logger2.warn("Skipping task with invalid handler config", { taskId: row.taskId, error: handlerResult.error.message });
456
- continue;
802
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_invalidPersistedTask", { params: { taskId: row.taskId, error: handlerResult.error.message } }));
457
803
  }
458
804
  const retryResult = row.retry == null ? { success: true, data: void 0 } : TaskRetryPolicySchema.safeParse(row.retry);
459
805
  if (!retryResult.success) {
460
- logger2.warn("Skipping task with invalid retry policy", { taskId: row.taskId, error: retryResult.error.message });
461
- continue;
806
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_invalidPersistedTask", { params: { taskId: row.taskId, error: retryResult.error.message } }));
462
807
  }
463
808
  tasks.push({
464
809
  id: row.taskId,
465
810
  name: row.taskName,
466
811
  ...row.description ? { description: row.description } : {},
467
812
  cron: row.cron,
813
+ ...row.timezone ? { timezone: row.timezone } : {},
468
814
  enabled: row.enabled,
815
+ idempotent: row.idempotent,
469
816
  deleteAfterRun: row.deleteAfterRun,
470
817
  ...retryResult.data ? { retry: retryResult.data } : {},
471
818
  params: paramsResult.data,
@@ -485,382 +832,101 @@ var SchedulerTaskRepository = class extends BaseReldbCrudRepository {
485
832
  }
486
833
  }
487
834
  };
488
- var compiledHandlerCache = /* @__PURE__ */ new Map();
489
- function createCacheKey(config) {
490
- const keySource = `${config.code}:${config.timeout ?? 0}`;
491
- return createHash("sha256").update(keySource).digest("hex");
492
- }
493
- function clearJsTaskHandlerCache() {
494
- compiledHandlerCache.clear();
495
- }
496
- function compileJsTaskHandler(config) {
497
- const cacheKey = createCacheKey(config);
498
- const cachedHandler = compiledHandlerCache.get(cacheKey);
499
- if (cachedHandler)
500
- return ok(cachedHandler);
835
+ function parseCronExpression(expression, timezone) {
501
836
  try {
502
- const script = new Script(`(${config.code})`);
503
- const candidate = script.runInNewContext({});
504
- if (typeof candidate !== "function") {
505
- return err(
506
- HaiSchedulerError.JS_COMPILE_FAILED,
507
- schedulerM("scheduler_jsCompileFailed", { params: { error: "Compiled result is not a function" } })
508
- );
509
- }
510
- const handler = async (context) => {
511
- const functionResult = candidate(context);
512
- if (!config.timeout || config.timeout <= 0)
513
- return functionResult;
514
- return await new Promise((resolve, reject) => {
515
- const timer = setTimeout(() => {
516
- reject(new Error(`JS task timed out after ${config.timeout}ms`));
517
- }, config.timeout);
518
- Promise.resolve(functionResult).then(
519
- (result) => {
520
- clearTimeout(timer);
521
- resolve(result);
522
- },
523
- (error) => {
524
- clearTimeout(timer);
525
- reject(error);
526
- }
527
- );
528
- });
529
- };
530
- compiledHandlerCache.set(cacheKey, handler);
531
- return ok(handler);
532
- } catch (error) {
837
+ const cron = new Cron(expression, { legacyMode: false, timezone: timezone ?? "UTC" });
838
+ return ok(cron);
839
+ } catch {
533
840
  return err(
534
- HaiSchedulerError.JS_COMPILE_FAILED,
535
- schedulerM("scheduler_jsCompileFailed", {
536
- params: { error: error instanceof Error ? error.message : String(error) }
537
- }),
538
- error
841
+ HaiSchedulerError.INVALID_CRON,
842
+ schedulerM("scheduler_invalidCron", { params: { expression } })
539
843
  );
540
844
  }
541
845
  }
542
846
 
543
- // src/scheduler-executor.ts
544
- var logger3 = core.logger.child({ module: "scheduler", scope: "executor" });
545
- var currentLogRepo = null;
546
- var currentCleanupPolicy = {};
547
- function setLogRepository(repo, cleanupPolicy = {}) {
548
- currentLogRepo = repo;
549
- currentCleanupPolicy = { ...cleanupPolicy };
847
+ // src/scheduler-functions.ts
848
+ var logger3 = core.logger.child({ module: "scheduler", scope: "functions" });
849
+ var taskRegistry = /* @__PURE__ */ new Map();
850
+ var cronCache = /* @__PURE__ */ new Map();
851
+ var persistedTaskIds = /* @__PURE__ */ new Set();
852
+ var definitionEpoch = 0;
853
+ var definitionTail = Promise.resolve();
854
+ var definitionLifetime = new AbortController();
855
+ function withTaskDefinitions(operation) {
856
+ const signal = definitionLifetime.signal;
857
+ const result = definitionTail.then(() => signal.aborted ? err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing")) : operation(signal));
858
+ definitionTail = result.then(() => void 0, () => void 0);
859
+ return result;
550
860
  }
551
- function sanitizeUrl(url) {
552
- try {
553
- const parsedUrl = new URL(url);
554
- if (parsedUrl.password)
555
- parsedUrl.password = "***";
556
- if (parsedUrl.username)
557
- parsedUrl.username = "***";
558
- return parsedUrl.toString();
559
- } catch {
560
- return "(invalid url)";
561
- }
861
+ async function drainTaskDefinitions() {
862
+ await definitionTail;
562
863
  }
563
- function resolveTaskType(task, hooks) {
564
- if (task.handler)
565
- return task.handler.kind;
566
- if (hooks.onTaskExecute)
567
- return "hook";
568
- return "hook";
864
+ function cancelTaskDefinitionReads() {
865
+ definitionLifetime.abort();
569
866
  }
570
- function createTaskContext(task, trigger) {
571
- return {
572
- task,
573
- taskId: task.id,
574
- params: task.params ?? {},
575
- trigger
576
- };
867
+ var currentHooks = {};
868
+ function getTaskRegistry() {
869
+ return taskRegistry;
577
870
  }
578
- async function notifyTaskStart(hooks, event) {
579
- if (!hooks.onTaskStart)
580
- return;
581
- try {
582
- await hooks.onTaskStart(event);
583
- } catch (error) {
584
- logger3.warn("Task start hook failed", { taskId: event.task.id, error });
585
- }
871
+ function getTask(taskId) {
872
+ return taskRegistry.get(taskId);
586
873
  }
587
- async function notifyTaskInterrupted(hooks, event) {
588
- if (!hooks.onTaskInterrupted)
589
- return;
590
- try {
591
- await hooks.onTaskInterrupted(event);
592
- } catch (error) {
593
- logger3.warn("Task interrupted hook failed", { taskId: event.task.id, error });
594
- }
874
+ function hasTask(taskId) {
875
+ return taskRegistry.has(taskId);
595
876
  }
596
- async function notifyTaskFinish(hooks, event) {
597
- if (!hooks.onTaskFinish)
598
- return;
599
- try {
600
- await hooks.onTaskFinish(event);
601
- } catch (error) {
602
- logger3.warn("Task finish hook failed", { taskId: event.task.id, error });
603
- }
877
+ function setTask(taskId, task) {
878
+ definitionEpoch++;
879
+ taskRegistry.set(taskId, task);
604
880
  }
605
- async function saveExecutionLog(task, trigger, taskType, status, startedAt, finishedAt, result, error) {
606
- const log = {
607
- id: 0,
608
- taskId: task.id,
609
- taskName: task.name,
610
- taskType,
611
- triggerType: trigger.type,
612
- triggerSource: trigger.source,
613
- status,
614
- result,
615
- error,
616
- startedAt,
617
- finishedAt,
618
- duration: finishedAt - startedAt
619
- };
620
- if (!currentLogRepo)
621
- return log;
622
- await currentLogRepo.saveLog(log);
623
- const cleanupResult = await currentLogRepo.cleanupLogs(currentCleanupPolicy);
624
- if (!cleanupResult.success) {
625
- logger3.warn("Failed to cleanup execution logs", {
626
- taskId: task.id,
627
- error: cleanupResult.error.message,
628
- maxLogs: currentCleanupPolicy.maxLogs,
629
- retentionDays: currentCleanupPolicy.retentionDays
630
- });
631
- }
632
- return log;
881
+ function deleteTask(taskId) {
882
+ definitionEpoch++;
883
+ taskRegistry.delete(taskId);
633
884
  }
634
- async function saveInterruptedTaskLog(task, trigger, reason, taskType, startedAt, finishedAt) {
635
- return saveExecutionLog(task, trigger, taskType, "interrupted", startedAt, finishedAt, null, reason);
885
+ function getCron(taskId) {
886
+ return cronCache.get(taskId);
636
887
  }
637
- async function interruptTask(task, trigger, reason, hooks) {
638
- const startedAt = Date.now();
639
- const taskType = resolveTaskType(task, hooks);
640
- await notifyTaskStart(hooks, { task, trigger, startedAt });
641
- const finishedAt = Date.now();
642
- const interruptedLog = await saveInterruptedTaskLog(task, trigger, reason, taskType, startedAt, finishedAt);
643
- await notifyTaskInterrupted(hooks, {
644
- task,
645
- trigger,
646
- startedAt,
647
- interruptedAt: finishedAt,
648
- reason
649
- });
650
- return interruptedLog;
888
+ function setCron(taskId, cron) {
889
+ cronCache.set(taskId, cron);
651
890
  }
652
- async function executeJsTask(task, context) {
653
- const handler = task.handler;
654
- if (!handler || handler.kind !== "js") {
655
- return err(
656
- HaiSchedulerError.EXECUTION_FAILED,
657
- schedulerM("scheduler_invalidHandlerConfig", { params: { taskId: task.id } })
658
- );
659
- }
660
- const compileResult = compileJsTaskHandler(handler);
661
- if (!compileResult.success)
662
- return compileResult;
663
- try {
664
- const result = await compileResult.data(context);
665
- return ok(result !== void 0 ? JSON.stringify(result) : null);
666
- } catch (error) {
667
- const message = error instanceof Error ? error.message : String(error);
668
- logger3.error("JS task execution failed", { taskId: task.id, error: message });
669
- return err(
670
- HaiSchedulerError.JS_EXECUTION_FAILED,
671
- schedulerM("scheduler_jsExecutionFailed", { params: { error: message } }),
672
- error
673
- );
674
- }
891
+ function deleteCron(taskId) {
892
+ cronCache.delete(taskId);
675
893
  }
676
- async function executeApiTask(task, context) {
677
- const handler = task.handler;
678
- if (!handler || handler.kind !== "api") {
894
+ function setHooks(hooks) {
895
+ currentHooks = { ...hooks };
896
+ }
897
+ function clearHooks() {
898
+ currentHooks = {};
899
+ }
900
+ function getHooks() {
901
+ return currentHooks;
902
+ }
903
+ function resetTaskState() {
904
+ definitionLifetime = new AbortController();
905
+ definitionEpoch++;
906
+ persistedTaskIds.clear();
907
+ taskRegistry.clear();
908
+ cronCache.clear();
909
+ currentHooks = {};
910
+ }
911
+ function normalizeTaskDescription(description) {
912
+ if (description === void 0)
913
+ return void 0;
914
+ const trimmed = description.trim();
915
+ return trimmed.length > 0 ? trimmed : void 0;
916
+ }
917
+ function validateRetryPolicy(taskId, retry) {
918
+ if (!Number.isInteger(retry.maxAttempts) || retry.maxAttempts < 1 || retry.maxAttempts > 100) {
679
919
  return err(
680
920
  HaiSchedulerError.EXECUTION_FAILED,
681
- schedulerM("scheduler_invalidHandlerConfig", { params: { taskId: task.id } })
921
+ schedulerM("scheduler_invalidRetryConfig", { params: { taskId } })
682
922
  );
683
923
  }
684
- const { url, method = "GET", headers, body, timeout = 3e4 } = handler;
685
- const controller = new AbortController();
686
- const timer = setTimeout(() => controller.abort(), timeout);
687
- try {
688
- const response = await fetch(url, {
689
- method,
690
- headers: {
691
- ...headers,
692
- ...body !== void 0 ? { "Content-Type": "application/json" } : {}
693
- },
694
- signal: controller.signal,
695
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
696
- });
697
- clearTimeout(timer);
698
- const responseText = await response.text();
699
- if (!response.ok) {
700
- logger3.error("API task returned non-OK status", {
701
- taskId: context.taskId,
702
- status: response.status,
703
- url: sanitizeUrl(url)
704
- });
924
+ if (retry.backoffMs !== void 0) {
925
+ const hasInvalidBackoff = retry.backoffMs.some((ms) => !Number.isInteger(ms) || ms < 0);
926
+ if (hasInvalidBackoff) {
705
927
  return err(
706
- HaiSchedulerError.API_EXECUTION_FAILED,
707
- schedulerM("scheduler_apiExecutionFailed", {
708
- params: { error: `HTTP ${response.status}: ${responseText.slice(0, 200)}` }
709
- })
710
- );
711
- }
712
- return ok(responseText || null);
713
- } catch (error) {
714
- clearTimeout(timer);
715
- const message = error instanceof Error ? error.message : String(error);
716
- logger3.error("API task execution failed", { taskId: context.taskId, error: message, url: sanitizeUrl(url) });
717
- return err(
718
- HaiSchedulerError.API_EXECUTION_FAILED,
719
- schedulerM("scheduler_apiExecutionFailed", { params: { error: message } }),
720
- error
721
- );
722
- }
723
- }
724
- async function executeHookTask(task, context, hooks, startedAt) {
725
- if (!hooks.onTaskExecute) {
726
- return err(
727
- HaiSchedulerError.EXECUTION_FAILED,
728
- schedulerM("scheduler_taskHandlerMissing", { params: { taskId: task.id } })
729
- );
730
- }
731
- const executeEvent = {
732
- task,
733
- trigger: context.trigger,
734
- startedAt,
735
- context
736
- };
737
- try {
738
- const result = await hooks.onTaskExecute(executeEvent);
739
- return ok(result !== void 0 ? JSON.stringify(result) : null);
740
- } catch (error) {
741
- const message = error instanceof Error ? error.message : String(error);
742
- logger3.error("Task execute hook failed", { taskId: task.id, error: message });
743
- return err(
744
- HaiSchedulerError.HOOK_EXECUTION_FAILED,
745
- schedulerM("scheduler_hookExecutionFailed", { params: { error: message } }),
746
- error
747
- );
748
- }
749
- }
750
- async function executeTask(task, trigger, hooks) {
751
- const startedAt = Date.now();
752
- const taskType = resolveTaskType(task, hooks);
753
- const context = createTaskContext(task, trigger);
754
- await notifyTaskStart(hooks, { task, trigger, startedAt });
755
- let executionResult;
756
- let shouldNotifyInterrupted = false;
757
- if (!task.handler) {
758
- executionResult = await executeHookTask(task, context, hooks, startedAt);
759
- shouldNotifyInterrupted = !executionResult.success;
760
- } else if (task.handler.kind === "api") {
761
- executionResult = await executeApiTask(task, context);
762
- } else {
763
- executionResult = await executeJsTask(task, context);
764
- }
765
- const finishedAt = Date.now();
766
- const status = executionResult.success ? "success" : shouldNotifyInterrupted ? "interrupted" : "failed";
767
- const log = await saveExecutionLog(
768
- task,
769
- trigger,
770
- taskType,
771
- status,
772
- startedAt,
773
- finishedAt,
774
- executionResult.success ? executionResult.data : null,
775
- executionResult.success ? null : executionResult.error.message
776
- );
777
- if (!executionResult.success && shouldNotifyInterrupted) {
778
- await notifyTaskInterrupted(hooks, {
779
- task,
780
- trigger,
781
- startedAt,
782
- interruptedAt: finishedAt,
783
- reason: executionResult.error.message
784
- });
785
- }
786
- if (status !== "interrupted")
787
- await notifyTaskFinish(hooks, { task, trigger, startedAt, finishedAt, log });
788
- return log;
789
- }
790
- function parseCronExpression(expression) {
791
- try {
792
- const cron = new Cron(expression, { legacyMode: false });
793
- return ok(cron);
794
- } catch {
795
- return err(
796
- HaiSchedulerError.INVALID_CRON,
797
- schedulerM("scheduler_invalidCron", { params: { expression } })
798
- );
799
- }
800
- }
801
-
802
- // src/scheduler-functions.ts
803
- var logger4 = core.logger.child({ module: "scheduler", scope: "functions" });
804
- var taskRegistry = /* @__PURE__ */ new Map();
805
- var cronCache = /* @__PURE__ */ new Map();
806
- var currentHooks = {};
807
- function getTaskRegistry() {
808
- return taskRegistry;
809
- }
810
- function getTask(taskId) {
811
- return taskRegistry.get(taskId);
812
- }
813
- function hasTask(taskId) {
814
- return taskRegistry.has(taskId);
815
- }
816
- function setTask(taskId, task) {
817
- taskRegistry.set(taskId, task);
818
- }
819
- function deleteTask(taskId) {
820
- taskRegistry.delete(taskId);
821
- }
822
- function getCron(taskId) {
823
- return cronCache.get(taskId);
824
- }
825
- function setCron(taskId, cron) {
826
- cronCache.set(taskId, cron);
827
- }
828
- function deleteCron(taskId) {
829
- cronCache.delete(taskId);
830
- }
831
- function setHooks(hooks) {
832
- currentHooks = { ...hooks };
833
- }
834
- function clearHooks() {
835
- currentHooks = {};
836
- }
837
- function getHooks() {
838
- return currentHooks;
839
- }
840
- function resetTaskState() {
841
- taskRegistry.clear();
842
- cronCache.clear();
843
- currentHooks = {};
844
- }
845
- function normalizeTaskDescription(description) {
846
- if (description === void 0)
847
- return void 0;
848
- const trimmed = description.trim();
849
- return trimmed.length > 0 ? trimmed : void 0;
850
- }
851
- function validateRetryPolicy(taskId, retry) {
852
- if (!Number.isInteger(retry.maxAttempts) || retry.maxAttempts < 1) {
853
- return err(
854
- HaiSchedulerError.EXECUTION_FAILED,
855
- schedulerM("scheduler_invalidRetryConfig", { params: { taskId } })
856
- );
857
- }
858
- if (retry.backoffMs !== void 0) {
859
- const hasInvalidBackoff = retry.backoffMs.some((ms) => !Number.isInteger(ms) || ms < 0);
860
- if (hasInvalidBackoff) {
861
- return err(
862
- HaiSchedulerError.EXECUTION_FAILED,
863
- schedulerM("scheduler_invalidRetryConfig", { params: { taskId } })
928
+ HaiSchedulerError.EXECUTION_FAILED,
929
+ schedulerM("scheduler_invalidRetryConfig", { params: { taskId } })
864
930
  );
865
931
  }
866
932
  }
@@ -870,49 +936,82 @@ function validateRetryPolicy(taskId, retry) {
870
936
  });
871
937
  }
872
938
  async function loadPersistedTasks(taskRepo2) {
939
+ return withTaskDefinitions((signal) => refreshTaskDefinitions(taskRepo2, signal));
940
+ }
941
+ async function refreshTaskDefinitions(taskRepo2, signal) {
873
942
  if (!taskRepo2)
874
- return;
875
- const loadResult = await taskRepo2.loadTasks();
876
- if (!loadResult.success) {
877
- logger4.warn("Failed to load persisted tasks", { error: loadResult.error.message });
878
- return;
943
+ return ok(void 0);
944
+ const epoch = definitionEpoch;
945
+ return refreshPersistedTasks(taskRepo2, epoch, signal);
946
+ }
947
+ async function refreshPersistedTasks(taskRepo2, epoch, signal) {
948
+ let cancel = () => {
949
+ };
950
+ const cancelled = new Promise((resolve) => {
951
+ cancel = () => resolve(err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing")));
952
+ signal.addEventListener("abort", cancel, { once: true });
953
+ if (signal.aborted)
954
+ cancel();
955
+ });
956
+ let loadResult;
957
+ try {
958
+ loadResult = await Promise.race([taskRepo2.loadTasks(), cancelled]);
959
+ } finally {
960
+ signal.removeEventListener("abort", cancel);
879
961
  }
880
- let loadedCount = 0;
962
+ if (!loadResult.success)
963
+ return loadResult;
964
+ if (signal.aborted)
965
+ return err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing"));
966
+ if (epoch !== definitionEpoch)
967
+ return err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_definitionsChanged"));
968
+ const nextTasks = new Map([...taskRegistry].filter(([id]) => !persistedTaskIds.has(id)));
969
+ const nextCrons = new Map([...cronCache].filter(([id]) => !persistedTaskIds.has(id)));
881
970
  for (const task of loadResult.data) {
882
- const registerResult = await registerTask(task);
883
- if (registerResult.success) {
884
- loadedCount++;
885
- logger4.debug("Loaded persisted task", { taskId: task.id, taskName: task.name });
886
- continue;
887
- }
888
- logger4.warn("Failed to load persisted task", { taskId: task.id, error: registerResult.error.message });
971
+ if (!task.id)
972
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_taskIdEmpty"));
973
+ if (nextTasks.has(task.id))
974
+ return err(HaiSchedulerError.TASK_ALREADY_EXISTS, schedulerM("scheduler_taskAlreadyExists", { params: { taskId: task.id } }));
975
+ const cronResult = parseCronExpression(task.cron, task.timezone);
976
+ if (!cronResult.success)
977
+ return cronResult;
978
+ nextTasks.set(task.id, task);
979
+ nextCrons.set(task.id, cronResult.data);
889
980
  }
890
- if (loadedCount > 0)
891
- logger4.info("Loaded persisted tasks", { count: loadedCount });
981
+ definitionEpoch++;
982
+ taskRegistry.clear();
983
+ cronCache.clear();
984
+ persistedTaskIds.clear();
985
+ for (const [id, task] of nextTasks)
986
+ taskRegistry.set(id, task);
987
+ for (const [id, cron] of nextCrons)
988
+ cronCache.set(id, cron);
989
+ for (const task of loadResult.data)
990
+ persistedTaskIds.add(task.id);
991
+ return ok(void 0);
892
992
  }
893
993
  async function loadConfigTasks(tasks) {
894
- let loadedCount = 0;
895
994
  for (const task of tasks) {
896
- if (!task.id) {
897
- logger4.warn("Skipping config task with empty id");
898
- continue;
899
- }
900
- if (hasTask(task.id)) {
901
- logger4.debug("Skipping config task, already registered from DB", { taskId: task.id });
902
- continue;
903
- }
904
995
  const registerResult = await registerTask(task);
905
- if (registerResult.success) {
906
- loadedCount++;
907
- logger4.debug("Loaded config task", { taskId: task.id, taskName: task.name });
908
- continue;
909
- }
910
- logger4.warn("Failed to load config task", { taskId: task.id, error: registerResult.error.message });
996
+ if (!registerResult.success)
997
+ return registerResult;
911
998
  }
912
- if (loadedCount > 0)
913
- logger4.info("Loaded config tasks", { count: loadedCount });
999
+ return ok(void 0);
914
1000
  }
915
1001
  async function registerTask(task, taskRepo2) {
1002
+ return withTaskDefinitions(async (signal) => {
1003
+ const refreshed = await refreshTaskDefinitions(taskRepo2 ?? null, signal);
1004
+ if (!refreshed.success)
1005
+ return refreshed;
1006
+ if (signal.aborted)
1007
+ return err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing"));
1008
+ return registerTaskDefinition(task, taskRepo2);
1009
+ });
1010
+ }
1011
+ async function registerTaskDefinition(task, taskRepo2) {
1012
+ if (task.handler && !TaskHandlerConfigSchema.safeParse(task.handler).success || task.idempotent !== void 0 && typeof task.idempotent !== "boolean") {
1013
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_invalidHandlerConfig", { params: { taskId: task.id } }));
1014
+ }
916
1015
  if (!task.id) {
917
1016
  return err(
918
1017
  HaiSchedulerError.EXECUTION_FAILED,
@@ -925,7 +1024,7 @@ async function registerTask(task, taskRepo2) {
925
1024
  schedulerM("scheduler_taskAlreadyExists", { params: { taskId: task.id } })
926
1025
  );
927
1026
  }
928
- const cronResult = parseCronExpression(task.cron);
1027
+ const cronResult = parseCronExpression(task.cron, task.timezone);
929
1028
  if (!cronResult.success)
930
1029
  return cronResult;
931
1030
  const retryResult = task.retry ? validateRetryPolicy(task.id, task.retry) : ok(void 0);
@@ -934,51 +1033,75 @@ async function registerTask(task, taskRepo2) {
934
1033
  const normalizedTask = {
935
1034
  ...task,
936
1035
  description: normalizeTaskDescription(task.description),
1036
+ timezone: task.timezone,
937
1037
  enabled: task.enabled !== false,
1038
+ idempotent: task.idempotent === true,
938
1039
  deleteAfterRun: task.deleteAfterRun === true,
939
1040
  retry: retryResult.data,
940
1041
  params: task.params ?? {}
941
1042
  };
942
- setTask(task.id, normalizedTask);
943
- setCron(task.id, cronResult.data);
944
1043
  if (taskRepo2) {
945
1044
  const saveResult = await taskRepo2.saveTask(normalizedTask);
946
1045
  if (!saveResult.success) {
947
- logger4.warn("Failed to persist task definition, rolling back in-memory registration", { taskId: task.id, error: saveResult.error.message });
948
- deleteTask(task.id);
949
- deleteCron(task.id);
1046
+ logger3.warn("Failed to persist task definition", { taskId: task.id, error: saveResult.error.message });
950
1047
  return err(
951
1048
  HaiSchedulerError.DB_SAVE_FAILED,
952
1049
  schedulerM("scheduler_dbSaveFailed", { params: { error: saveResult.error.message } }),
953
1050
  saveResult.error
954
1051
  );
955
1052
  }
1053
+ persistedTaskIds.add(task.id);
956
1054
  }
1055
+ setTask(task.id, normalizedTask);
1056
+ setCron(task.id, cronResult.data);
957
1057
  return ok(void 0);
958
1058
  }
959
- async function unregisterTask(taskId, taskRepo2) {
1059
+ async function unregisterTask(taskId, taskRepo2, expected) {
1060
+ return withTaskDefinitions(async (signal) => {
1061
+ const refreshed = await refreshTaskDefinitions(taskRepo2 ?? null, signal);
1062
+ if (!refreshed.success)
1063
+ return refreshed;
1064
+ if (signal.aborted)
1065
+ return err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing"));
1066
+ return unregisterTaskDefinition(taskId, taskRepo2, expected);
1067
+ });
1068
+ }
1069
+ async function unregisterTaskDefinition(taskId, taskRepo2, expected) {
960
1070
  if (!hasTask(taskId)) {
961
1071
  return err(
962
1072
  HaiSchedulerError.TASK_NOT_FOUND,
963
1073
  schedulerM("scheduler_taskNotFound", { params: { taskId } })
964
1074
  );
965
1075
  }
966
- deleteTask(taskId);
967
- deleteCron(taskId);
968
1076
  if (taskRepo2) {
969
- const deleteResult = await taskRepo2.deleteTask(taskId);
1077
+ const deleteResult = await taskRepo2.deleteTask(taskId, expected);
970
1078
  if (!deleteResult.success) {
971
- logger4.warn("Failed to delete persisted task definition", { taskId, error: deleteResult.error.message });
1079
+ logger3.warn("Failed to delete persisted task definition", { taskId, error: deleteResult.error.message });
972
1080
  return err(
973
1081
  HaiSchedulerError.DB_SAVE_FAILED,
974
1082
  schedulerM("scheduler_dbSaveFailed", { params: { error: deleteResult.error.message } }),
975
1083
  deleteResult.error
976
1084
  );
977
1085
  }
1086
+ if (expected && !deleteResult.data)
1087
+ return ok(void 0);
978
1088
  }
1089
+ deleteTask(taskId);
1090
+ deleteCron(taskId);
1091
+ persistedTaskIds.delete(taskId);
979
1092
  return ok(void 0);
980
1093
  }
981
1094
  async function updateRegisteredTask(taskId, updates, taskRepo2) {
1095
+ return withTaskDefinitions(async (signal) => {
1096
+ const refreshed = await refreshTaskDefinitions(taskRepo2 ?? null, signal);
1097
+ if (!refreshed.success)
1098
+ return refreshed;
1099
+ if (signal.aborted)
1100
+ return err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing"));
1101
+ return updateTaskDefinition(taskId, updates, taskRepo2);
1102
+ });
1103
+ }
1104
+ async function updateTaskDefinition(taskId, updates, taskRepo2) {
982
1105
  const existingTask = getTask(taskId);
983
1106
  if (!existingTask) {
984
1107
  return err(
@@ -986,12 +1109,14 @@ async function updateRegisteredTask(taskId, updates, taskRepo2) {
986
1109
  schedulerM("scheduler_taskNotFound", { params: { taskId } })
987
1110
  );
988
1111
  }
989
- const existingCron = getCron(taskId);
990
- if (updates.cron !== void 0) {
991
- const cronResult = parseCronExpression(updates.cron);
1112
+ let updatedCron = getCron(taskId);
1113
+ if (updates.cron !== void 0 || updates.timezone !== void 0) {
1114
+ const cronExpression = updates.cron ?? existingTask.cron;
1115
+ const timezone = updates.timezone === null ? void 0 : updates.timezone ?? existingTask.timezone;
1116
+ const cronResult = parseCronExpression(cronExpression, timezone);
992
1117
  if (!cronResult.success)
993
1118
  return cronResult;
994
- setCron(taskId, cronResult.data);
1119
+ updatedCron = cronResult.data;
995
1120
  }
996
1121
  let normalizedRetry;
997
1122
  if (updates.retry !== void 0) {
@@ -1004,31 +1129,32 @@ async function updateRegisteredTask(taskId, updates, taskRepo2) {
1004
1129
  normalizedRetry = retryResult.data;
1005
1130
  }
1006
1131
  }
1007
- const normalizedDescription = updates.description !== void 0 ? normalizeTaskDescription(updates.description) : void 0;
1132
+ const normalizedDescription = updates.description !== void 0 ? normalizeTaskDescription(updates.description) ?? "" : void 0;
1008
1133
  const normalizedUpdates = {
1009
1134
  ...updates,
1010
1135
  ...updates.description !== void 0 ? { description: normalizedDescription } : {},
1011
1136
  ...updates.retry !== void 0 ? { retry: normalizedRetry } : {}
1012
1137
  };
1138
+ if (updates.handler && !TaskHandlerConfigSchema.safeParse(updates.handler).success || updates.idempotent !== void 0 && typeof updates.idempotent !== "boolean") {
1139
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_invalidHandlerConfig", { params: { taskId } }));
1140
+ }
1013
1141
  const updatedTask = {
1014
1142
  ...existingTask,
1015
1143
  ...normalizedUpdates.name !== void 0 ? { name: normalizedUpdates.name } : {},
1016
- ...normalizedUpdates.description !== void 0 ? { description: normalizedUpdates.description } : {},
1144
+ ...normalizedUpdates.description !== void 0 ? { description: normalizedUpdates.description || void 0 } : {},
1017
1145
  ...normalizedUpdates.cron !== void 0 ? { cron: normalizedUpdates.cron } : {},
1146
+ ...normalizedUpdates.timezone !== void 0 ? { timezone: normalizedUpdates.timezone ?? void 0 } : {},
1018
1147
  ...normalizedUpdates.enabled !== void 0 ? { enabled: normalizedUpdates.enabled } : {},
1148
+ ...normalizedUpdates.idempotent !== void 0 ? { idempotent: normalizedUpdates.idempotent } : {},
1019
1149
  ...normalizedUpdates.deleteAfterRun !== void 0 ? { deleteAfterRun: normalizedUpdates.deleteAfterRun } : {},
1020
1150
  ...normalizedUpdates.retry !== void 0 ? { retry: normalizedUpdates.retry ?? void 0 } : {},
1021
1151
  ...normalizedUpdates.params !== void 0 ? { params: normalizedUpdates.params } : {},
1022
1152
  ...normalizedUpdates.handler !== void 0 ? { handler: normalizedUpdates.handler ?? void 0 } : {}
1023
1153
  };
1024
- setTask(taskId, updatedTask);
1025
1154
  if (taskRepo2) {
1026
1155
  const updateResult = await taskRepo2.updateTask(taskId, normalizedUpdates);
1027
1156
  if (!updateResult.success) {
1028
- logger4.warn("Failed to update persisted task definition, rolling back in-memory update", { taskId, error: updateResult.error.message });
1029
- setTask(taskId, existingTask);
1030
- if (updates.cron !== void 0 && existingCron)
1031
- setCron(taskId, existingCron);
1157
+ logger3.warn("Failed to update persisted task definition", { taskId, error: updateResult.error.message });
1032
1158
  return err(
1033
1159
  HaiSchedulerError.DB_SAVE_FAILED,
1034
1160
  schedulerM("scheduler_dbSaveFailed", { params: { error: updateResult.error.message } }),
@@ -1036,6 +1162,9 @@ async function updateRegisteredTask(taskId, updates, taskRepo2) {
1036
1162
  );
1037
1163
  }
1038
1164
  }
1165
+ setTask(taskId, updatedTask);
1166
+ if (updatedCron)
1167
+ setCron(taskId, updatedCron);
1039
1168
  return ok(void 0);
1040
1169
  }
1041
1170
  async function queryTaskLogs(logRepo2, options) {
@@ -1047,158 +1176,740 @@ async function queryTaskLogs(logRepo2, options) {
1047
1176
  }
1048
1177
  return logRepo2.queryLogs(options);
1049
1178
  }
1179
+ var compiledHandlerCache = /* @__PURE__ */ new Map();
1180
+ function createCacheKey(config) {
1181
+ const keySource = `${config.code}:${config.timeout ?? 0}`;
1182
+ return createHash("sha256").update(keySource).digest("hex");
1183
+ }
1184
+ function clearJsTaskHandlerCache() {
1185
+ compiledHandlerCache.clear();
1186
+ }
1187
+ function compileJsTaskHandler(config) {
1188
+ const cacheKey = createCacheKey(config);
1189
+ const cachedHandler = compiledHandlerCache.get(cacheKey);
1190
+ if (cachedHandler)
1191
+ return ok(cachedHandler);
1192
+ try {
1193
+ void new Script(`(${config.code})`);
1194
+ const handler = async (context, signal) => {
1195
+ signal?.throwIfAborted();
1196
+ return await new Promise((resolve, reject) => {
1197
+ const timeout = config.timeout ?? 3e4;
1198
+ const worker = new Worker(new URL("./scheduler-js-worker.js", import.meta.url), {
1199
+ workerData: { code: config.code, context },
1200
+ execArgv: []
1201
+ });
1202
+ let settled = false;
1203
+ let timer;
1204
+ const aborted = () => finish(new Error(schedulerM("scheduler_closing")));
1205
+ function finish(error, result) {
1206
+ if (settled)
1207
+ return;
1208
+ settled = true;
1209
+ clearTimeout(timer);
1210
+ signal?.removeEventListener("abort", aborted);
1211
+ void worker.terminate().then(() => error ? reject(error) : resolve(result), reject);
1212
+ }
1213
+ timer = setTimeout(() => finish(new Error(schedulerM("scheduler_jsTimedOut", { params: { timeout } }))), timeout);
1214
+ signal?.addEventListener("abort", aborted, { once: true });
1215
+ worker.once("error", (error) => finish(error instanceof Error ? error : new Error(String(error))));
1216
+ worker.once("exit", (code) => finish(new Error(`JS worker exited before returning a result (${code})`)));
1217
+ worker.once("message", (message) => {
1218
+ if (message.success)
1219
+ finish(void 0, message.data);
1220
+ else
1221
+ finish(new Error(message.message));
1222
+ });
1223
+ });
1224
+ };
1225
+ compiledHandlerCache.set(cacheKey, handler);
1226
+ return ok(handler);
1227
+ } catch (error) {
1228
+ return err(
1229
+ HaiSchedulerError.JS_COMPILE_FAILED,
1230
+ schedulerM("scheduler_jsCompileFailed", {
1231
+ params: { error: error instanceof Error ? error.message : String(error) }
1232
+ }),
1233
+ error
1234
+ );
1235
+ }
1236
+ }
1237
+ function migrateScheduler(options = {}) {
1238
+ const steps = [{
1239
+ version: 1,
1240
+ name: "explicit-task-idempotency",
1241
+ async needed(sql) {
1242
+ const columns = await schemaColumns(reldb, "hai_scheduler_tasks", sql);
1243
+ return columns.success ? ok(columns.data.length > 0 && !columns.data.includes("idempotent")) : columns;
1244
+ },
1245
+ async apply(sql) {
1246
+ return sql.execute("ALTER TABLE hai_scheduler_tasks ADD COLUMN idempotent BOOLEAN NOT NULL DEFAULT FALSE");
1247
+ }
1248
+ }, {
1249
+ version: 2,
1250
+ name: "execution-history-snapshots",
1251
+ async needed(sql) {
1252
+ const columns = await schemaColumns(reldb, "hai_scheduler_logs", sql);
1253
+ if (!columns.success)
1254
+ return columns;
1255
+ if (columns.data.length && !columns.data.includes("payload"))
1256
+ return ok(true);
1257
+ const archive = await schemaColumns(reldb, "hai_scheduler_logs_alpha65", sql);
1258
+ if (!archive.success)
1259
+ return archive;
1260
+ if (!archive.data.length)
1261
+ return ok(false);
1262
+ if (!columns.data.length)
1263
+ return ok(true);
1264
+ const identity = reldb.config?.type === "mysql" ? "CAST(n.id AS BINARY)=CAST(CONCAT('legacy:',CAST(a.id AS CHAR)) AS BINARY)" : "n.id='legacy:' || CAST(a.id AS TEXT)";
1265
+ const missing = await sql.get(`SELECT id FROM hai_scheduler_logs_alpha65 a WHERE NOT EXISTS (SELECT 1 FROM hai_scheduler_logs n WHERE ${identity}) LIMIT 1`);
1266
+ return missing.success ? ok(Boolean(missing.data)) : missing;
1267
+ },
1268
+ async apply(sql) {
1269
+ const columns = await schemaColumns(reldb, "hai_scheduler_logs", sql);
1270
+ if (!columns.success)
1271
+ return columns;
1272
+ if (columns.data.length && !columns.data.includes("payload")) {
1273
+ const archive = await schemaColumns(reldb, "hai_scheduler_logs_alpha65", sql);
1274
+ if (!archive.success)
1275
+ return archive;
1276
+ if (archive.data.length)
1277
+ return err(HaiCommonError.INIT_FAILED, "Scheduler archive already exists");
1278
+ const renamed = await sql.execute("ALTER TABLE hai_scheduler_logs RENAME TO hai_scheduler_logs_alpha65");
1279
+ if (!renamed.success)
1280
+ return renamed;
1281
+ }
1282
+ const text = reldb.config?.type === "mysql" ? "VARCHAR(255)" : "TEXT";
1283
+ const json = reldb.config?.type === "postgresql" ? "JSONB" : reldb.config?.type === "mysql" ? "JSON" : "TEXT";
1284
+ const created = await sql.execute(`CREATE TABLE IF NOT EXISTS hai_scheduler_logs (id ${text} NOT NULL,occurrence_id ${text},task_id ${text} NOT NULL,task_name ${text} NOT NULL,task_type ${text} NOT NULL,trigger_type ${text} NOT NULL,trigger_source ${text},status ${text} NOT NULL,payload ${json} NOT NULL,started_at BIGINT NOT NULL,finished_at BIGINT NOT NULL,duration INTEGER NOT NULL,CONSTRAINT pk_hai_scheduler_log_v2 PRIMARY KEY(id))`);
1285
+ if (!created.success)
1286
+ return created;
1287
+ for (let offset = 0; ; offset += 100) {
1288
+ const rows = await sql.query(`SELECT CAST(id AS ${reldb.config?.type === "mysql" ? "CHAR" : "TEXT"}) AS id,task_id,task_name,task_type,trigger_type,trigger_source,status,result,error,started_at,finished_at,duration FROM hai_scheduler_logs_alpha65 ORDER BY id LIMIT 100 OFFSET ?`, [offset]);
1289
+ if (!rows.success)
1290
+ return rows;
1291
+ for (const row of rows.data) {
1292
+ const id = `legacy:${row.id}`;
1293
+ const existing = await sql.get("SELECT id FROM hai_scheduler_logs WHERE id=?", [id]);
1294
+ if (!existing.success)
1295
+ return existing;
1296
+ if (existing.data)
1297
+ continue;
1298
+ const payload = { id, taskId: row.task_id, taskName: row.task_name, taskType: row.task_type, triggerType: row.trigger_type, triggerSource: row.trigger_source, status: row.status, result: row.result, error: row.error, startedAt: Number(row.started_at), finishedAt: Number(row.finished_at), duration: Number(row.duration), persistence: { status: "persisted" } };
1299
+ const copied = await sql.execute("INSERT INTO hai_scheduler_logs(id,task_id,task_name,task_type,trigger_type,trigger_source,status,payload,started_at,finished_at,duration) VALUES(?,?,?,?,?,?,?,?,?,?,?)", [id, row.task_id, row.task_name, row.task_type, row.trigger_type, row.trigger_source, row.status, JSON.stringify(payload), row.started_at, row.finished_at, row.duration]);
1300
+ if (!copied.success)
1301
+ return copied;
1302
+ }
1303
+ if (rows.data.length < 100)
1304
+ return ok(void 0);
1305
+ }
1306
+ }
1307
+ }];
1308
+ return migrateSchema(reldb, "scheduler", steps, options);
1309
+ }
1310
+
1311
+ // src/scheduler-cancellation.ts
1312
+ async function waitWithSignal(operation, signal) {
1313
+ signal.throwIfAborted();
1314
+ return new Promise((resolve, reject) => {
1315
+ const aborted = () => reject(signal.reason);
1316
+ signal.addEventListener("abort", aborted, { once: true });
1317
+ Promise.resolve().then(operation).then(resolve, reject).finally(() => {
1318
+ signal.removeEventListener("abort", aborted);
1319
+ });
1320
+ });
1321
+ }
1322
+
1323
+ // src/scheduler-executor.ts
1324
+ var logger4 = core.logger.child({ module: "scheduler", scope: "executor" });
1325
+ function resolveTaskType(task, hooks) {
1326
+ if (task.handler)
1327
+ return task.handler.kind;
1328
+ if (hooks.onTaskExecute)
1329
+ return "hook";
1330
+ return "hook";
1331
+ }
1332
+ function createTaskContext(task, trigger, execution) {
1333
+ return {
1334
+ ...execution,
1335
+ task,
1336
+ taskId: task.id,
1337
+ params: task.params ?? {},
1338
+ trigger
1339
+ };
1340
+ }
1341
+ async function notifyTaskStart(hooks, event) {
1342
+ if (!hooks.onTaskStart)
1343
+ return;
1344
+ try {
1345
+ await waitWithSignal(() => hooks.onTaskStart(event), event.signal);
1346
+ } catch (error) {
1347
+ logger4.warn("Task start hook failed", { taskId: event.task.id, error });
1348
+ }
1349
+ }
1350
+ async function notifyTaskInterrupted(hooks, event) {
1351
+ if (!hooks.onTaskInterrupted)
1352
+ return;
1353
+ try {
1354
+ await waitWithSignal(() => hooks.onTaskInterrupted(event), event.signal);
1355
+ } catch (error) {
1356
+ logger4.warn("Task interrupted hook failed", { taskId: event.task.id, error });
1357
+ }
1358
+ }
1359
+ async function notifyTaskFinish(hooks, event) {
1360
+ if (!hooks.onTaskFinish)
1361
+ return;
1362
+ try {
1363
+ await waitWithSignal(() => hooks.onTaskFinish(event), event.signal);
1364
+ } catch (error) {
1365
+ logger4.warn("Task finish hook failed", { taskId: event.task.id, error });
1366
+ }
1367
+ }
1368
+ function createExecutionLog(task, trigger, taskType, status, startedAt, finishedAt, result, error, occurrenceId) {
1369
+ const log = {
1370
+ id: crypto.randomUUID(),
1371
+ persistence: { status: "unconfirmed" },
1372
+ taskId: task.id,
1373
+ taskName: task.name,
1374
+ taskType,
1375
+ triggerType: trigger.type,
1376
+ triggerSource: trigger.source,
1377
+ status,
1378
+ result,
1379
+ error,
1380
+ startedAt,
1381
+ finishedAt,
1382
+ duration: finishedAt - startedAt,
1383
+ ...occurrenceId ? { occurrenceId } : {}
1384
+ };
1385
+ return log;
1386
+ }
1387
+ async function createInterruptedTaskLog(task, trigger, reason, taskType, startedAt, finishedAt) {
1388
+ return createExecutionLog(task, trigger, taskType, "interrupted", startedAt, finishedAt, null, reason);
1389
+ }
1390
+ async function interruptTask(task, trigger, reason, hooks, signal = new AbortController().signal) {
1391
+ const startedAt = Date.now();
1392
+ const taskType = resolveTaskType(task, hooks);
1393
+ await notifyTaskStart(hooks, { task, trigger, startedAt, signal });
1394
+ const finishedAt = Date.now();
1395
+ const interruptedLog = await createInterruptedTaskLog(task, trigger, reason, taskType, startedAt, finishedAt);
1396
+ await notifyTaskInterrupted(hooks, {
1397
+ task,
1398
+ trigger,
1399
+ startedAt,
1400
+ interruptedAt: finishedAt,
1401
+ signal,
1402
+ reason
1403
+ });
1404
+ return interruptedLog;
1405
+ }
1406
+ async function executeJsTask(task, context, signal = new AbortController().signal) {
1407
+ const handler = task.handler;
1408
+ if (!handler || handler.kind !== "js") {
1409
+ return err(
1410
+ HaiSchedulerError.EXECUTION_FAILED,
1411
+ schedulerM("scheduler_invalidHandlerConfig", { params: { taskId: task.id } })
1412
+ );
1413
+ }
1414
+ const compileResult = compileJsTaskHandler(handler);
1415
+ if (!compileResult.success)
1416
+ return compileResult;
1417
+ try {
1418
+ const result = await compileResult.data(context, signal);
1419
+ return ok(result !== void 0 ? JSON.stringify(result) : null);
1420
+ } catch (error) {
1421
+ const message = error instanceof Error ? error.message : String(error);
1422
+ logger4.error("JS task execution failed", { taskId: task.id, error: message });
1423
+ return err(
1424
+ HaiSchedulerError.JS_EXECUTION_FAILED,
1425
+ schedulerM("scheduler_jsExecutionFailed", { params: { error: message } }),
1426
+ error
1427
+ );
1428
+ }
1429
+ }
1430
+ async function executeApiTask(task, context, signal = new AbortController().signal) {
1431
+ const handler = task.handler;
1432
+ if (!handler || handler.kind !== "api") {
1433
+ return err(
1434
+ HaiSchedulerError.EXECUTION_FAILED,
1435
+ schedulerM("scheduler_invalidHandlerConfig", { params: { taskId: task.id } })
1436
+ );
1437
+ }
1438
+ const { url, method = "GET", headers, body, timeout = 3e4, maxResponseBytes = 1024 * 1024 } = handler;
1439
+ if (!Number.isSafeInteger(maxResponseBytes) || maxResponseBytes <= 0)
1440
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_invalidHandlerConfig", { params: { taskId: task.id } }));
1441
+ const controller = new AbortController();
1442
+ const timer = setTimeout(() => controller.abort(), timeout);
1443
+ try {
1444
+ const requestHeaders = new Headers(headers);
1445
+ if (body !== void 0)
1446
+ requestHeaders.set("Content-Type", "application/json");
1447
+ if (context.occurrenceId) {
1448
+ requestHeaders.set("Idempotency-Key", context.occurrenceId);
1449
+ requestHeaders.set("X-Scheduler-Sequence", String(context.sequence));
1450
+ requestHeaders.set("X-Scheduler-Attempt", String(context.attempt));
1451
+ requestHeaders.set("X-Scheduler-Task", encodeURIComponent(context.taskId));
1452
+ }
1453
+ const response = await fetch(url, {
1454
+ method,
1455
+ headers: requestHeaders,
1456
+ signal: AbortSignal.any([signal, controller.signal]),
1457
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
1458
+ });
1459
+ let receivedBytes = 0;
1460
+ let responseText = "";
1461
+ const reader = response.body?.getReader();
1462
+ if (reader) {
1463
+ const decoder = new TextDecoder();
1464
+ try {
1465
+ while (true) {
1466
+ const chunk = await reader.read();
1467
+ if (chunk.done)
1468
+ break;
1469
+ receivedBytes += chunk.value.byteLength;
1470
+ if (receivedBytes > maxResponseBytes) {
1471
+ controller.abort();
1472
+ return err(HaiSchedulerError.API_EXECUTION_FAILED, schedulerM("scheduler_apiResponseTooLarge", { params: { maxResponseBytes } }));
1473
+ }
1474
+ responseText += decoder.decode(chunk.value, { stream: true });
1475
+ }
1476
+ responseText += decoder.decode();
1477
+ } finally {
1478
+ reader.releaseLock();
1479
+ }
1480
+ }
1481
+ if (!response.ok) {
1482
+ logger4.error("API task returned non-OK status", {
1483
+ taskId: context.taskId,
1484
+ status: response.status,
1485
+ url: core.sanitize.sanitizeUrl(url)
1486
+ });
1487
+ return err(
1488
+ HaiSchedulerError.API_EXECUTION_FAILED,
1489
+ schedulerM("scheduler_apiExecutionFailed", {
1490
+ params: { error: `HTTP ${response.status}: ${responseText.slice(0, 200)}` }
1491
+ })
1492
+ );
1493
+ }
1494
+ return ok(responseText || null);
1495
+ } catch (error) {
1496
+ const message = error instanceof Error ? error.message : String(error);
1497
+ logger4.error("API task execution failed", { taskId: context.taskId, error: message, url: core.sanitize.sanitizeUrl(url) });
1498
+ return err(
1499
+ HaiSchedulerError.API_EXECUTION_FAILED,
1500
+ schedulerM("scheduler_apiExecutionFailed", { params: { error: message } }),
1501
+ error
1502
+ );
1503
+ } finally {
1504
+ clearTimeout(timer);
1505
+ }
1506
+ }
1507
+ async function executeHookTask(task, context, hooks, startedAt, signal) {
1508
+ if (!hooks.onTaskExecute) {
1509
+ return err(
1510
+ HaiSchedulerError.EXECUTION_FAILED,
1511
+ schedulerM("scheduler_taskHandlerMissing", { params: { taskId: task.id } })
1512
+ );
1513
+ }
1514
+ const executeEvent = {
1515
+ task,
1516
+ trigger: context.trigger,
1517
+ startedAt,
1518
+ context,
1519
+ signal
1520
+ };
1521
+ try {
1522
+ const result = await waitWithSignal(() => hooks.onTaskExecute(executeEvent), signal);
1523
+ return ok(result !== void 0 ? JSON.stringify(result) : null);
1524
+ } catch (error) {
1525
+ const message = error instanceof Error ? error.message : String(error);
1526
+ logger4.error("Task execute hook failed", { taskId: task.id, error: message });
1527
+ return err(
1528
+ HaiSchedulerError.HOOK_EXECUTION_FAILED,
1529
+ schedulerM("scheduler_hookExecutionFailed", { params: { error: message } }),
1530
+ error
1531
+ );
1532
+ }
1533
+ }
1534
+ async function executeTask(task, trigger, hooks, signal = new AbortController().signal, execution) {
1535
+ const startedAt = Date.now();
1536
+ const taskType = resolveTaskType(task, hooks);
1537
+ const context = createTaskContext(task, trigger, execution);
1538
+ await notifyTaskStart(hooks, { task, trigger, startedAt, signal, context });
1539
+ let executionResult;
1540
+ let shouldNotifyInterrupted = false;
1541
+ if (signal.aborted) {
1542
+ executionResult = err(HaiSchedulerError.EXECUTION_FAILED, schedulerM("scheduler_closing"));
1543
+ shouldNotifyInterrupted = true;
1544
+ } else if (!task.handler) {
1545
+ executionResult = await executeHookTask(task, context, hooks, startedAt, signal);
1546
+ shouldNotifyInterrupted = !hooks.onTaskExecute || !executionResult.success && executionResult.error.cause instanceof Error && executionResult.error.cause.name === "SchedulerTaskSkippedError";
1547
+ } else if (task.handler.kind === "api") {
1548
+ executionResult = await executeApiTask(task, context, signal);
1549
+ } else {
1550
+ executionResult = await executeJsTask(task, context, signal);
1551
+ }
1552
+ shouldNotifyInterrupted ||= signal.aborted;
1553
+ const finishedAt = Date.now();
1554
+ let status = executionResult.success ? "success" : shouldNotifyInterrupted ? "interrupted" : "failed";
1555
+ if (execution?.executionToken && !task.idempotent && !executionResult.success)
1556
+ status = "unknown";
1557
+ const log = createExecutionLog(
1558
+ task,
1559
+ trigger,
1560
+ taskType,
1561
+ status,
1562
+ startedAt,
1563
+ finishedAt,
1564
+ executionResult.success ? executionResult.data : null,
1565
+ executionResult.success ? null : executionResult.error.message,
1566
+ context.occurrenceId
1567
+ );
1568
+ if (!executionResult.success && shouldNotifyInterrupted) {
1569
+ await notifyTaskInterrupted(hooks, {
1570
+ task,
1571
+ trigger,
1572
+ startedAt,
1573
+ interruptedAt: finishedAt,
1574
+ signal,
1575
+ reason: executionResult.error.message,
1576
+ context
1577
+ });
1578
+ }
1579
+ if (status !== "interrupted" && !signal.aborted)
1580
+ await notifyTaskFinish(hooks, { task, trigger, startedAt, finishedAt, log, signal, context });
1581
+ return log;
1582
+ }
1583
+
1584
+ // src/scheduler-runner.ts
1050
1585
  var logger5 = core.logger.child({ module: "scheduler", scope: "runner" });
1051
1586
  var runningTasks = /* @__PURE__ */ new Set();
1587
+ var activeRuns = /* @__PURE__ */ new Map();
1588
+ var activeRepairs = /* @__PURE__ */ new Set();
1052
1589
  var tickTimer = null;
1590
+ var tickInProgress = null;
1053
1591
  var lastTickMinute = -1;
1054
1592
  var currentNodeId = "";
1055
- var currentLockTtlSec = 300;
1593
+ var currentLeaseMs = 3e5;
1056
1594
  var currentTaskRepo = null;
1057
- function configureLock(nodeId, lockTtlSec) {
1595
+ var currentExecutionRepo = null;
1596
+ var currentLogRepo = null;
1597
+ var currentCleanupPolicy = {};
1598
+ function setLogRepository(repo, policy = {}) {
1599
+ currentLogRepo = repo;
1600
+ currentCleanupPolicy = { ...policy };
1601
+ }
1602
+ var publishedLogSchema = z.object({
1603
+ id: z.uuid(),
1604
+ occurrenceId: z.string().regex(/^[a-f\d]{64}$/),
1605
+ taskId: z.string(),
1606
+ taskName: z.string(),
1607
+ taskType: z.enum(["api", "js", "hook"]),
1608
+ triggerType: z.enum(["manual", "scheduled"]),
1609
+ triggerSource: z.string().nullable(),
1610
+ status: z.enum(["success", "failed", "interrupted", "unknown"]),
1611
+ result: z.string().nullable(),
1612
+ error: z.string().nullable(),
1613
+ startedAt: z.number().safe(),
1614
+ finishedAt: z.number().safe(),
1615
+ duration: z.number().safe(),
1616
+ persistence: z.object({ status: z.enum(["pending", "persisted", "unconfirmed"]), error: z.object({ code: z.string(), message: z.string() }).optional() })
1617
+ });
1618
+ function repairExecutionLogs(id) {
1619
+ const operation = projectExecutionLogs(id);
1620
+ activeRepairs.add(operation);
1621
+ void operation.finally(() => activeRepairs.delete(operation)).catch(() => {
1622
+ });
1623
+ return operation;
1624
+ }
1625
+ async function projectExecutionLogs(id) {
1626
+ const execution = currentExecutionRepo;
1627
+ const logs = currentLogRepo;
1628
+ const cleanupPolicy = currentCleanupPolicy;
1629
+ if (!execution || !logs)
1630
+ return err(HaiSchedulerError.LOG_PERSIST_FAILED, schedulerM("scheduler_logPersistFailed"));
1631
+ try {
1632
+ const found = await execution.byOccurrence(id);
1633
+ if (!found.success || !found.data || ["claimed", "running"].includes(found.data.status))
1634
+ return err(HaiSchedulerError.LOG_PERSIST_FAILED, schedulerM("scheduler_logPersistFailed"));
1635
+ const row = found.data;
1636
+ if (row.logPersistence === "persisted")
1637
+ return ok(void 0);
1638
+ const parsed = z.array(publishedLogSchema).min(1).max(101).safeParse(JSON.parse(row.logsJson ?? "null"));
1639
+ if (!parsed.success || parsed.data.some((log) => log.occurrenceId !== id || log.taskId !== row.taskId))
1640
+ return err(HaiSchedulerError.LOG_PERSIST_FAILED, schedulerM("scheduler_logPersistFailed"));
1641
+ for (const log of parsed.data) {
1642
+ const saved = await logs.saveLog(log);
1643
+ if (!saved.success)
1644
+ return saved;
1645
+ }
1646
+ const confirmed = await execution.confirmLogs(row);
1647
+ if (!confirmed.success)
1648
+ return err(HaiSchedulerError.LOG_PERSIST_FAILED, schedulerM("scheduler_logPersistFailed"));
1649
+ const cleanup = await logs.cleanupLogs(cleanupPolicy);
1650
+ if (!cleanup.success)
1651
+ logger5.warn("Execution logs persisted but retention cleanup failed", { occurrenceId: id, errorCode: cleanup.error.code });
1652
+ return ok(void 0);
1653
+ } catch {
1654
+ return err(HaiSchedulerError.LOG_PERSIST_FAILED, schedulerM("scheduler_logPersistFailed"));
1655
+ }
1656
+ }
1657
+ function configureExecution(repo, nodeId = "", leaseMs = 3e5) {
1658
+ currentExecutionRepo = repo;
1058
1659
  currentNodeId = nodeId;
1059
- currentLockTtlSec = lockTtlSec;
1660
+ currentLeaseMs = leaseMs;
1060
1661
  }
1061
1662
  function setTaskRepository(repo) {
1062
1663
  currentTaskRepo = repo;
1063
1664
  }
1064
- function isTaskRunning(taskId) {
1065
- return runningTasks.has(taskId);
1066
- }
1067
1665
  function isTimerRunning() {
1068
1666
  return tickTimer !== null;
1069
1667
  }
1070
1668
  function resetRunner() {
1071
1669
  runningTasks.clear();
1072
- if (tickTimer) {
1073
- clearInterval(tickTimer);
1074
- tickTimer = null;
1075
- }
1670
+ stopTimer();
1076
1671
  lastTickMinute = -1;
1077
- currentNodeId = "";
1078
- currentLockTtlSec = 300;
1079
1672
  currentTaskRepo = null;
1673
+ configureExecution(null);
1674
+ }
1675
+ async function sleep(ms, signal) {
1676
+ if (ms <= 0 || signal.aborted)
1677
+ return;
1678
+ await new Promise((resolve) => {
1679
+ let timer;
1680
+ const finish = () => {
1681
+ clearTimeout(timer);
1682
+ signal.removeEventListener("abort", finish);
1683
+ resolve();
1684
+ };
1685
+ timer = setTimeout(finish, ms);
1686
+ signal.addEventListener("abort", finish, { once: true });
1687
+ });
1080
1688
  }
1081
- async function sleep(ms) {
1082
- if (ms <= 0)
1689
+ async function drainRunner() {
1690
+ stopTimer();
1691
+ for (const controller of activeRuns.values())
1692
+ controller.abort(new Error(schedulerM("scheduler_closing")));
1693
+ await Promise.allSettled([...activeRuns.keys()]);
1694
+ await Promise.allSettled([...activeRepairs]);
1695
+ }
1696
+ async function tick() {
1697
+ const timer = tickTimer;
1698
+ const repository = currentTaskRepo;
1699
+ const executionRepo2 = currentExecutionRepo;
1700
+ if (!timer || tickInProgress === timer)
1083
1701
  return;
1084
- await new Promise((resolve) => setTimeout(resolve, ms));
1085
- }
1086
- function resolveRetryBackoffMs(task, attempt) {
1087
- const backoff = task.retry?.backoffMs;
1088
- if (!backoff || backoff.length === 0)
1089
- return 0;
1090
- const index = Math.min(Math.max(attempt - 2, 0), backoff.length - 1);
1091
- return backoff[index] ?? 0;
1092
- }
1093
- function tick() {
1094
- const now = /* @__PURE__ */ new Date();
1095
- const currentMinute = Math.floor(now.getTime() / 6e4);
1702
+ tickInProgress = timer;
1703
+ const isCurrent = () => tickTimer === timer && currentTaskRepo === repository && currentExecutionRepo === executionRepo2;
1704
+ try {
1705
+ const refreshed = await loadPersistedTasks(repository);
1706
+ if (!refreshed.success || !isCurrent())
1707
+ return;
1708
+ const expired = await executionRepo2?.expired();
1709
+ if (!isCurrent())
1710
+ return;
1711
+ if (expired?.success) {
1712
+ for (const row of expired.data) {
1713
+ const task = getTask(row.taskId);
1714
+ if (!task) {
1715
+ await executionRepo2?.isolateExpired(row);
1716
+ if (!isCurrent())
1717
+ return;
1718
+ continue;
1719
+ }
1720
+ if (task && !runningTasks.has(task.id)) {
1721
+ let trigger;
1722
+ try {
1723
+ trigger = JSON.parse(row.triggerJson);
1724
+ } catch {
1725
+ await executionRepo2?.isolateExpired(row);
1726
+ if (!isCurrent())
1727
+ return;
1728
+ continue;
1729
+ }
1730
+ void runTask(task, trigger.minute, trigger, void 0, row).catch((error) => logger5.warn("Execution recovery failed", { taskId: task.id, error }));
1731
+ }
1732
+ }
1733
+ }
1734
+ const now = await executionRepo2?.currentTime();
1735
+ if (now?.success && isCurrent())
1736
+ scheduleDueTasks(now.data);
1737
+ } finally {
1738
+ if (tickInProgress === timer)
1739
+ tickInProgress = null;
1740
+ }
1741
+ }
1742
+ function scheduleDueTasks(databaseNow) {
1743
+ const currentMinute = Math.floor(databaseNow / 6e4);
1096
1744
  if (currentMinute === lastTickMinute)
1097
1745
  return;
1098
1746
  lastTickMinute = currentMinute;
1099
1747
  for (const [taskId, task] of getTaskRegistry()) {
1100
- if (task.enabled === false)
1748
+ if (task.enabled === false || runningTasks.has(taskId))
1101
1749
  continue;
1102
- const cron = getCron(taskId);
1103
- if (!cron || !cron.match(now))
1750
+ if (!getCron(taskId)?.match(new Date(currentMinute * 6e4)))
1104
1751
  continue;
1105
- if (runningTasks.has(taskId)) {
1106
- logger5.debug("Skipping task already running", { taskId, taskName: task.name });
1107
- continue;
1108
- }
1109
- void runTask(task, currentMinute, { type: "scheduled", source: null }).catch((error) => {
1110
- logger5.error("Unhandled task execution error", { taskId, error });
1111
- });
1752
+ void runTask(task, currentMinute, { type: "scheduled", source: null }).catch((error) => logger5.error("Unhandled task execution error", { taskId, error }));
1112
1753
  }
1113
1754
  }
1114
- async function runTask(task, minuteTimestamp, trigger = { type: "manual", source: null }) {
1115
- const lockKey = minuteTimestamp !== void 0 ? `hai:scheduler:${task.id}:${minuteTimestamp}` : void 0;
1116
- if (cache.isInitialized && lockKey) {
1117
- const lockResult = await cache.lock.acquire(lockKey, { ttl: currentLockTtlSec, owner: currentNodeId });
1118
- if (!lockResult.success) {
1119
- logger5.warn("Failed to acquire distributed lock, interrupting task", { taskId: task.id, error: lockResult.error.message });
1120
- return interruptTask(
1121
- task,
1122
- trigger,
1123
- schedulerM("scheduler_lockAcquireFailed", { params: { taskId: task.id } }),
1124
- getHooks()
1125
- );
1755
+ function runTask(task, minuteTimestamp, trigger = { type: "manual", source: null }, options, recovery) {
1756
+ const controller = new AbortController();
1757
+ const run = runTaskExecution(task, minuteTimestamp, trigger, controller, options, recovery);
1758
+ activeRuns.set(run, controller);
1759
+ void run.finally(() => activeRuns.delete(run)).catch(() => {
1760
+ });
1761
+ return run;
1762
+ }
1763
+ async function runTaskExecution(task, minute, trigger, controller, options, recovery) {
1764
+ const repository = currentTaskRepo;
1765
+ const executionRepo2 = currentExecutionRepo;
1766
+ const logRepository = currentLogRepo;
1767
+ const hooks = getHooks();
1768
+ const leaseMs = currentLeaseMs;
1769
+ const occurrenceId = recovery?.occurrenceId ?? executionId(task.id, trigger.type, minute === void 0 ? options?.idempotencyKey ?? randomUUID() : String(minute));
1770
+ const interrupted = async (reason, observationOnly = false) => {
1771
+ const log = { ...await interruptTask(task, trigger, reason, {}, controller.signal), occurrenceId };
1772
+ if (observationOnly && logRepository) {
1773
+ const saved = await logRepository.saveLog(log);
1774
+ log.persistence = saved.success ? { status: "persisted" } : { status: "unconfirmed", error: { code: String(saved.error.code), message: saved.error.message } };
1126
1775
  }
1127
- if (!lockResult.data) {
1128
- logger5.debug("Skipping task, another node holds the lock", { taskId: task.id, minuteTimestamp });
1129
- return interruptTask(
1130
- task,
1131
- trigger,
1132
- schedulerM("scheduler_lockAcquireFailed", { params: { taskId: task.id } }),
1133
- getHooks()
1134
- );
1776
+ return log;
1777
+ };
1778
+ if (!executionRepo2)
1779
+ return interrupted(schedulerM("scheduler_executionStateFailed"), true);
1780
+ const claimed = await executionRepo2.claim(task, occurrenceId, { ...trigger, ...minute !== void 0 ? { minute } : {} }, currentNodeId, leaseMs);
1781
+ if (!claimed.success)
1782
+ return interrupted(claimed.error.message, true);
1783
+ if (!claimed.data)
1784
+ return interrupted(schedulerM("scheduler_taskRunning", { params: { taskId: task.id } }), true);
1785
+ const row = claimed.data;
1786
+ if (!["claimed", "running"].includes(row.status)) {
1787
+ if (minute === void 0) {
1788
+ try {
1789
+ const log = row.logJson ? JSON.parse(row.logJson) : {
1790
+ id: randomUUID(),
1791
+ persistence: { status: "unconfirmed" },
1792
+ taskId: row.taskId,
1793
+ taskName: task.name,
1794
+ taskType: task.handler?.kind ?? "hook",
1795
+ triggerType: trigger.type,
1796
+ triggerSource: trigger.source,
1797
+ status: "interrupted",
1798
+ result: null,
1799
+ error: null,
1800
+ startedAt: row.createdAt,
1801
+ finishedAt: row.updatedAt,
1802
+ duration: row.updatedAt - row.createdAt
1803
+ };
1804
+ const status = row.status === "discarded" ? "interrupted" : row.status;
1805
+ return { ...log, status, error: status === "success" ? null : log.error, occurrenceId };
1806
+ } catch {
1807
+ return interrupted(schedulerM("scheduler_executionStateFailed"));
1808
+ }
1135
1809
  }
1136
- }
1137
- if (runningTasks.has(task.id)) {
1138
- return interruptTask(
1139
- task,
1140
- trigger,
1141
- schedulerM("scheduler_taskRunning", { params: { taskId: task.id } }),
1142
- getHooks()
1143
- );
1810
+ return interrupted(schedulerM("scheduler_occurrenceHandled", { params: { taskId: task.id } }), true);
1144
1811
  }
1145
1812
  runningTasks.add(task.id);
1813
+ let timer;
1814
+ let renewing;
1815
+ let stopped = false;
1816
+ let lost = false;
1817
+ const renew = async () => {
1818
+ try {
1819
+ const result = await executionRepo2.renew(row, leaseMs);
1820
+ lost = !result.success;
1821
+ } catch {
1822
+ lost = true;
1823
+ }
1824
+ if (lost) {
1825
+ controller.abort(new Error(schedulerM("scheduler_executionStateFailed")));
1826
+ } else if (!stopped) {
1827
+ timer = setTimeout(() => {
1828
+ renewing = renew();
1829
+ }, Math.max(1, Math.floor(leaseMs / 3)));
1830
+ }
1831
+ };
1832
+ timer = setTimeout(() => {
1833
+ renewing = renew();
1834
+ }, Math.max(1, Math.floor(leaseMs / 3)));
1146
1835
  try {
1147
- const maxAttempts = Math.max(1, task.retry?.maxAttempts ?? 1);
1148
- let log = null;
1149
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
1150
- log = await executeTask(task, trigger, getHooks());
1151
- if (log.status !== "failed")
1836
+ let log;
1837
+ const attempts = [];
1838
+ for (; row.attemptCount < row.maxAttempts; ) {
1839
+ if (controller.signal.aborted)
1152
1840
  break;
1153
- if (attempt >= maxAttempts)
1841
+ const refreshed = await loadPersistedTasks(repository);
1842
+ const latest = getTask(task.id);
1843
+ let unchanged = false;
1844
+ try {
1845
+ unchanged = latest !== void 0 && isDeepStrictEqual(JSON.parse(JSON.stringify(latest)), JSON.parse(row.snapshot));
1846
+ } catch {
1847
+ }
1848
+ if (!refreshed.success || !latest || latest.enabled === false || !unchanged) {
1849
+ log = await interrupted(schedulerM("scheduler_taskNoLongerDue", { params: { taskId: task.id } }));
1850
+ if (row.attemptCount > 0)
1851
+ log.status = "unknown";
1154
1852
  break;
1155
- const backoffMs = resolveRetryBackoffMs(task, attempt + 1);
1156
- logger5.warn("Retrying failed task execution", {
1157
- taskId: task.id,
1158
- attempt,
1159
- maxAttempts,
1160
- backoffMs
1161
- });
1162
- await sleep(backoffMs);
1853
+ }
1854
+ task = latest;
1855
+ if (!task.handler && !hooks.onTaskExecute) {
1856
+ log = { ...await interruptTask(task, trigger, schedulerM("scheduler_taskHandlerMissing", { params: { taskId: task.id } }), hooks, controller.signal), occurrenceId };
1857
+ break;
1858
+ }
1859
+ const begun = await executionRepo2.begin(row, leaseMs);
1860
+ if (!begun.success) {
1861
+ lost = true;
1862
+ break;
1863
+ }
1864
+ log = await executeTask(task, trigger, hooks, controller.signal, { occurrenceId, executionToken: row.owner, sequence: row.sequence, attempt: row.attemptCount });
1865
+ log.occurrenceId = occurrenceId;
1866
+ attempts.push(log);
1867
+ if (log.status !== "failed" || !row.idempotent || row.attemptCount >= row.maxAttempts)
1868
+ break;
1869
+ const delays = task.retry?.backoffMs ?? [];
1870
+ const delay = delays[Math.min(row.attemptCount - 1, Math.max(0, delays.length - 1))] ?? 0;
1871
+ await sleep(delay, controller.signal);
1163
1872
  }
1164
- if (!log) {
1165
- return interruptTask(
1166
- task,
1167
- trigger,
1168
- schedulerM("scheduler_executionFailed", { params: { error: "Task execution produced no log" } }),
1169
- getHooks()
1170
- );
1873
+ if (!log)
1874
+ log = await interrupted(schedulerM("scheduler_executionStateFailed"));
1875
+ if (lost) {
1876
+ return { ...log, status: "unknown", persistence: { status: "unconfirmed" }, error: schedulerM("scheduler_executionUnknown"), occurrenceId };
1171
1877
  }
1172
- if (log.status === "failed")
1173
- logger5.warn("Task execution failed", { taskId: task.id, error: log.error });
1174
- else if (log.status === "interrupted")
1175
- logger5.debug("Task execution interrupted", { taskId: task.id, error: log.error });
1878
+ if (controller.signal.aborted && row.attemptCount > 0)
1879
+ log = { ...log, status: "unknown", error: schedulerM("scheduler_executionUnknown") };
1880
+ const currentAttempt = attempts.findIndex((attempt) => attempt.id === log.id);
1881
+ if (currentAttempt >= 0)
1882
+ attempts[currentAttempt] = log;
1176
1883
  else
1177
- logger5.debug("Task execution succeeded", { taskId: task.id, duration: log.duration });
1178
- if (task.deleteAfterRun === true) {
1179
- const unregisterResult = await unregisterTask(task.id, currentTaskRepo);
1180
- if (!unregisterResult.success) {
1181
- logger5.warn("Failed to auto-delete one-time task after run", {
1182
- taskId: task.id,
1183
- error: unregisterResult.error.message
1184
- });
1185
- } else {
1186
- logger5.info("Auto-deleted one-time task after run", { taskId: task.id });
1187
- }
1884
+ attempts.push(log);
1885
+ const published = attempts.map((attempt) => ({ ...attempt, persistence: { status: "pending" } }));
1886
+ const finished = await executionRepo2.finish(row, { ...log, persistence: { status: "pending" } }, published);
1887
+ if (!finished.success)
1888
+ return { ...log, status: "unknown", persistence: { status: "unconfirmed" }, error: finished.error.message, occurrenceId };
1889
+ const projected = await repairExecutionLogs(occurrenceId);
1890
+ log.persistence = projected.success ? { status: "persisted" } : { status: "pending", error: { code: String(projected.error.code), message: projected.error.message } };
1891
+ if (!projected.success)
1892
+ logger5.warn("Execution completed with pending log persistence", { taskId: task.id, occurrenceId, errorCode: projected.error.code });
1893
+ if (task.deleteAfterRun && log.status === "success") {
1894
+ const refreshed = await loadPersistedTasks(repository);
1895
+ if (refreshed.success && isDeepStrictEqual(getTask(task.id), task))
1896
+ await unregisterTask(task.id, repository, task);
1188
1897
  }
1189
1898
  return log;
1190
1899
  } finally {
1900
+ stopped = true;
1901
+ clearTimeout(timer);
1902
+ await renewing;
1191
1903
  runningTasks.delete(task.id);
1192
1904
  }
1193
1905
  }
1194
1906
  function startTimer(tickInterval) {
1195
1907
  lastTickMinute = -1;
1196
- tickTimer = setInterval(() => tick(), tickInterval);
1908
+ tickTimer = setInterval(tick, tickInterval);
1197
1909
  }
1198
1910
  function stopTimer() {
1199
- if (!tickTimer)
1200
- return;
1201
- clearInterval(tickTimer);
1911
+ if (tickTimer)
1912
+ clearInterval(tickTimer);
1202
1913
  tickTimer = null;
1203
1914
  }
1204
1915
 
@@ -1206,33 +1917,38 @@ function stopTimer() {
1206
1917
  var logger6 = core.logger.child({ module: "scheduler", scope: "main" });
1207
1918
  var currentConfig = null;
1208
1919
  var initInProgress = false;
1920
+ var closeInProgress = null;
1209
1921
  var taskRepo = null;
1210
1922
  var logRepo = null;
1923
+ var executionRepo = null;
1924
+ var executionIdSchema = z.string().regex(/^[a-f\d]{64}$/);
1925
+ var executionListSchema = z.object({ limit: z.number().int().min(1).max(100).default(50), offset: z.number().int().min(0).max(1e6).default(0) });
1211
1926
  var notInitialized = core.module.createNotInitializedKit(
1212
1927
  HaiSchedulerError.NOT_INITIALIZED,
1213
1928
  () => schedulerM("scheduler_notInitialized")
1214
1929
  );
1215
1930
  async function initDatabase(parsed) {
1216
- if (!parsed.enableDb)
1217
- return parsed;
1218
1931
  if (!reldb.isInitialized) {
1219
1932
  logger6.error("enableDb is true but @h-ai/reldb is not initialized");
1220
1933
  throw new Error(schedulerM("scheduler_reldbNotInitialized"));
1221
1934
  }
1935
+ const migration = await migrateScheduler();
1936
+ if (!migration.success)
1937
+ throw migration.error;
1222
1938
  taskRepo = new SchedulerTaskRepository(reldb);
1223
1939
  logRepo = new SchedulerLogRepository(reldb);
1940
+ executionRepo = new SchedulerExecutionRepository(reldb);
1941
+ const ready = await executionRepo.count();
1942
+ if (!ready.success)
1943
+ throw new Error(schedulerM("scheduler_executionStateFailed"));
1224
1944
  setTaskRepository(taskRepo);
1225
1945
  setLogRepository(logRepo, {
1226
1946
  maxLogs: parsed.maxLogs,
1227
1947
  retentionDays: parsed.retentionDays
1228
1948
  });
1229
1949
  const nodeId = parsed.nodeId ?? crypto.randomUUID();
1230
- const lockTtlSec = Math.ceil(parsed.lockExpireMs / 1e3);
1231
- configureLock(nodeId, lockTtlSec);
1232
- if (cache.isInitialized)
1233
- logger6.info("Distributed lock configured (cache-based)", { nodeId, lockTtlSec });
1234
- else
1235
- logger6.warn("Cache module not initialized, distributed lock will be enabled when cache becomes available");
1950
+ configureExecution(executionRepo, nodeId, parsed.leaseMs);
1951
+ logger6.info("Shared execution repository configured", { nodeId, leaseMs: parsed.leaseMs });
1236
1952
  return { ...parsed, nodeId };
1237
1953
  }
1238
1954
  function normalizeTriggerInput(options) {
@@ -1242,6 +1958,49 @@ function normalizeTriggerInput(options) {
1242
1958
  };
1243
1959
  }
1244
1960
  var scheduler = {
1961
+ execution: {
1962
+ async get(id) {
1963
+ if (!currentConfig || !executionRepo)
1964
+ return notInitialized.result();
1965
+ if (!executionIdSchema.safeParse(id).success)
1966
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_executionInputInvalid"));
1967
+ const row = await executionRepo.byOccurrence(id);
1968
+ return row.success ? ok(row.data ? executionEntry(row.data) : null) : row;
1969
+ },
1970
+ async listUnknown(options) {
1971
+ if (!currentConfig || !executionRepo)
1972
+ return notInitialized.result();
1973
+ const parsed = executionListSchema.safeParse(options ?? {});
1974
+ if (!parsed.success)
1975
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_executionInputInvalid"));
1976
+ const rows = await executionRepo.unknown(parsed.data.limit, parsed.data.offset);
1977
+ return rows.success ? ok(rows.data.map(executionEntry)) : rows;
1978
+ },
1979
+ async listLogFailures(options) {
1980
+ if (!currentConfig || !executionRepo)
1981
+ return notInitialized.result();
1982
+ const parsed = executionListSchema.safeParse(options ?? {});
1983
+ if (!parsed.success)
1984
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_executionInputInvalid"));
1985
+ const rows = await executionRepo.pendingLogs(parsed.data.limit, parsed.data.offset);
1986
+ return rows.success ? ok(rows.data.map(executionEntry)) : rows;
1987
+ },
1988
+ async repairLog(id) {
1989
+ if (!currentConfig || !executionRepo || closeInProgress)
1990
+ return notInitialized.result();
1991
+ if (!executionIdSchema.safeParse(id).success)
1992
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_executionInputInvalid"));
1993
+ return repairExecutionLogs(id);
1994
+ },
1995
+ async resolveUnknown(id, resolution) {
1996
+ if (!currentConfig || !executionRepo)
1997
+ return notInitialized.result();
1998
+ const parsed = ExecutionResolutionSchema.safeParse(resolution);
1999
+ if (!executionIdSchema.safeParse(id).success || !parsed.success)
2000
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_executionInputInvalid"));
2001
+ return executionRepo.resolve(id, parsed.data.status, parsed.data.expectedUpdatedAt);
2002
+ }
2003
+ },
1245
2004
  async init(config) {
1246
2005
  if (initInProgress) {
1247
2006
  logger6.warn("Scheduler init already in progress, skipping concurrent call");
@@ -1252,6 +2011,8 @@ var scheduler = {
1252
2011
  }
1253
2012
  initInProgress = true;
1254
2013
  try {
2014
+ if (closeInProgress)
2015
+ await closeInProgress;
1255
2016
  if (currentConfig) {
1256
2017
  logger6.warn("Scheduler module is already initialized, reinitializing");
1257
2018
  await scheduler.close();
@@ -1270,9 +2031,16 @@ var scheduler = {
1270
2031
  try {
1271
2032
  currentConfig = await initDatabase(parseResult.data);
1272
2033
  setHooks(hooks);
1273
- await loadPersistedTasks(taskRepo);
1274
- if (tasks.length > 0)
1275
- await loadConfigTasks(tasks);
2034
+ const persistedResult = await loadPersistedTasks(taskRepo);
2035
+ if (!persistedResult.success) {
2036
+ await scheduler.close();
2037
+ return persistedResult;
2038
+ }
2039
+ const configResult = await loadConfigTasks(tasks);
2040
+ if (!configResult.success) {
2041
+ await scheduler.close();
2042
+ return configResult;
2043
+ }
1276
2044
  logger6.info("Scheduler module initialized", { enableDb: currentConfig.enableDb, taskCount: getTaskRegistry().size });
1277
2045
  return ok(void 0);
1278
2046
  } catch (error) {
@@ -1290,6 +2058,12 @@ var scheduler = {
1290
2058
  initInProgress = false;
1291
2059
  }
1292
2060
  },
2061
+ /** 刷新数据库任务投影,不执行任何任务。 */
2062
+ async refreshTasks() {
2063
+ if (!currentConfig)
2064
+ return notInitialized.result();
2065
+ return loadPersistedTasks(taskRepo);
2066
+ },
1293
2067
  async register(task) {
1294
2068
  if (!currentConfig)
1295
2069
  return notInitialized.result();
@@ -1344,6 +2118,15 @@ var scheduler = {
1344
2118
  async trigger(taskId, options) {
1345
2119
  if (!currentConfig)
1346
2120
  return notInitialized.result();
2121
+ const parsed = TriggerTaskSchema.safeParse(options ?? {});
2122
+ if (!parsed.success)
2123
+ return err(HaiSchedulerError.CONFIG_ERROR, schedulerM("scheduler_executionInputInvalid"));
2124
+ const config = currentConfig;
2125
+ const refreshed = await loadPersistedTasks(taskRepo);
2126
+ if (!refreshed.success)
2127
+ return refreshed;
2128
+ if (currentConfig !== config)
2129
+ return notInitialized.result();
1347
2130
  const task = getTask(taskId);
1348
2131
  if (!task) {
1349
2132
  return err(
@@ -1351,13 +2134,7 @@ var scheduler = {
1351
2134
  schedulerM("scheduler_taskNotFound", { params: { taskId } })
1352
2135
  );
1353
2136
  }
1354
- if (isTaskRunning(taskId)) {
1355
- return err(
1356
- HaiSchedulerError.EXECUTION_FAILED,
1357
- schedulerM("scheduler_taskRunning", { params: { taskId } })
1358
- );
1359
- }
1360
- const log = await runTask(task, void 0, normalizeTriggerInput(options));
2137
+ const log = await runTask(task, void 0, normalizeTriggerInput(parsed.data), parsed.data);
1361
2138
  return ok(log);
1362
2139
  },
1363
2140
  async getLogs(options) {
@@ -1393,24 +2170,33 @@ var scheduler = {
1393
2170
  return isTimerRunning();
1394
2171
  },
1395
2172
  async close() {
1396
- if (!currentConfig) {
1397
- logger6.info("Scheduler module already closed, skipping");
1398
- return;
1399
- }
2173
+ if (closeInProgress)
2174
+ return closeInProgress;
1400
2175
  logger6.info("Closing scheduler module");
1401
- stopTimer();
1402
- clearJsTaskHandlerCache();
1403
- resetTaskState();
1404
- resetRunner();
1405
- setLogRepository(null);
1406
- setTaskRepository(null);
1407
2176
  currentConfig = null;
1408
- taskRepo = null;
1409
- logRepo = null;
1410
- logger6.info("Scheduler module closed");
2177
+ stopTimer();
2178
+ cancelTaskDefinitionReads();
2179
+ closeInProgress = (async () => {
2180
+ await drainRunner();
2181
+ await drainTaskDefinitions();
2182
+ clearJsTaskHandlerCache();
2183
+ resetTaskState();
2184
+ resetRunner();
2185
+ setLogRepository(null);
2186
+ setTaskRepository(null);
2187
+ taskRepo = null;
2188
+ logRepo = null;
2189
+ executionRepo = null;
2190
+ logger6.info("Scheduler module closed");
2191
+ })();
2192
+ try {
2193
+ await closeInProgress;
2194
+ } finally {
2195
+ closeInProgress = null;
2196
+ }
1411
2197
  }
1412
2198
  };
1413
2199
 
1414
- export { HaiSchedulerError, SchedulerConfigSchema, scheduler };
2200
+ export { ExecutionResolutionSchema, HaiSchedulerError, SchedulerConfigSchema, TriggerTaskSchema, migrateScheduler, scheduler };
1415
2201
  //# sourceMappingURL=index.js.map
1416
2202
  //# sourceMappingURL=index.js.map