@h-ai/scheduler 0.1.0-alpha8 → 1.0.0-beta.1

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.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import * as _h_ai_core from '@h-ai/core';
3
3
  import { PaginationOptionsInput, HaiResult, PaginatedResult } from '@h-ai/core';
4
+ import * as _h_ai_reldb from '@h-ai/reldb';
4
5
 
5
6
  /**
6
7
  * @h-ai/scheduler — 配置 Schema
@@ -16,25 +17,106 @@ import { PaginationOptionsInput, HaiResult, PaginatedResult } from '@h-ai/core';
16
17
  *
17
18
  * @example
18
19
  * ```ts
19
- * const config = SchedulerConfigSchema.parse({
20
- * enableDb: true,
21
- * tickInterval: 1000,
22
- * })
20
+ * import { SchedulerConfigSchema } from '@h-ai/scheduler'
21
+ *
22
+ * const parsed = SchedulerConfigSchema.safeParse({ enableDb: true, tickInterval: 1000, leaseMs: 300000 })
23
+ * if (parsed.success) {
24
+ * const renewalPeriod = Math.floor(parsed.data.leaseMs / 3)
25
+ * }
23
26
  * ```
24
27
  */
25
28
  declare const SchedulerConfigSchema: z.ZodObject<{
26
- enableDb: z.ZodDefault<z.ZodBoolean>;
29
+ enableDb: z.ZodDefault<z.ZodLiteral<true>>;
27
30
  tickInterval: z.ZodDefault<z.ZodNumber>;
28
- lockExpireMs: z.ZodDefault<z.ZodNumber>;
31
+ leaseMs: z.ZodDefault<z.ZodNumber>;
29
32
  nodeId: z.ZodOptional<z.ZodString>;
30
33
  maxLogs: z.ZodOptional<z.ZodNumber>;
31
34
  retentionDays: z.ZodOptional<z.ZodNumber>;
32
35
  }, z.core.$strip>;
33
- /** 调度器配置类型 */
36
+ /**
37
+ * 手动触发边界,重复使用同一幂等键会命中同一个执行记录。
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * import { TriggerTaskSchema } from '@h-ai/scheduler'
42
+ *
43
+ * const parsed = TriggerTaskSchema.safeParse({ source: 'billing-console', idempotencyKey: 'billing-2026-10' })
44
+ * if (parsed.success) {
45
+ * const sameOccurrenceKey = parsed.data.idempotencyKey
46
+ * }
47
+ * ```
48
+ */
49
+ declare const TriggerTaskSchema: z.ZodObject<{
50
+ source: z.ZodOptional<z.ZodString>;
51
+ idempotencyKey: z.ZodOptional<z.ZodString>;
52
+ }, z.core.$strip>;
53
+ /**
54
+ * 可信服务端人工核对结果;必须先停止旧 runner,不能将未知执行直接重排。
55
+ *
56
+ * @example
57
+ * ```ts
58
+ * import { ExecutionResolutionSchema, scheduler } from '@h-ai/scheduler'
59
+ *
60
+ * // 可信运维流程已停止旧 runner 并核对实际外部结果。
61
+ * const pending = await scheduler.execution.listUnknown({ limit: 10 })
62
+ * if (!pending.success) throw new Error(pending.error.message)
63
+ * const entry = pending.data[0]
64
+ * if (entry) {
65
+ * const resolution = ExecutionResolutionSchema.parse({ status: 'discarded', expectedUpdatedAt: entry.updatedAt })
66
+ * const resolved = await scheduler.execution.resolveUnknown(entry.occurrenceId, resolution)
67
+ * if (!resolved.success) throw new Error(resolved.error.message)
68
+ * }
69
+ * ```
70
+ */
71
+ declare const ExecutionResolutionSchema: z.ZodObject<{
72
+ status: z.ZodEnum<{
73
+ success: "success";
74
+ discarded: "discarded";
75
+ }>;
76
+ expectedUpdatedAt: z.ZodNumber;
77
+ }, z.core.$strip>;
78
+ /**
79
+ * 调度器配置类型
80
+ *
81
+ * @example
82
+ * ```ts
83
+ * import type { SchedulerConfig } from '@h-ai/scheduler'
84
+ * import { SchedulerConfigSchema } from '@h-ai/scheduler'
85
+ *
86
+ * const config: SchedulerConfig = SchedulerConfigSchema.parse({ leaseMs: 60000 })
87
+ * const renewalInterval = config.leaseMs / 3
88
+ * ```
89
+ */
34
90
  type SchedulerConfig = z.infer<typeof SchedulerConfigSchema>;
35
- /** 调度器配置输入类型 */
91
+ /**
92
+ * 调度器配置输入类型
93
+ *
94
+ * @example
95
+ * ```ts
96
+ * import type { SchedulerConfigInput } from '@h-ai/scheduler'
97
+ * import { scheduler } from '@h-ai/scheduler'
98
+ *
99
+ * // 宿主已成功初始化共享 reldb。
100
+ * const config: SchedulerConfigInput = { leaseMs: 60000, retentionDays: 30 }
101
+ * const initialized = await scheduler.init(config)
102
+ * if (!initialized.success) throw new Error(initialized.error.message)
103
+ * ```
104
+ */
36
105
  type SchedulerConfigInput = z.input<typeof SchedulerConfigSchema>;
37
106
 
107
+ /**
108
+ * Scheduler 领域错误定义;业务调用先判断 success 再按错误码分支。
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * import { HaiSchedulerError, scheduler } from '@h-ai/scheduler'
113
+ *
114
+ * const result = await scheduler.trigger('missing-task')
115
+ * if (!result.success && result.error.code === HaiSchedulerError.TASK_NOT_FOUND.code) {
116
+ * const missingTask = true
117
+ * }
118
+ * ```
119
+ */
38
120
  declare const HaiSchedulerError: {
39
121
  readonly NOT_INITIALIZED: _h_ai_core.HaiErrorDef;
40
122
  readonly INIT_FAILED: _h_ai_core.HaiErrorDef;
@@ -48,27 +130,85 @@ declare const HaiSchedulerError: {
48
130
  readonly DB_SAVE_FAILED: _h_ai_core.HaiErrorDef;
49
131
  readonly ALREADY_RUNNING: _h_ai_core.HaiErrorDef;
50
132
  readonly NOT_RUNNING: _h_ai_core.HaiErrorDef;
51
- readonly LOCK_ACQUIRE_FAILED: _h_ai_core.HaiErrorDef;
52
133
  readonly JS_COMPILE_FAILED: _h_ai_core.HaiErrorDef;
53
134
  readonly HOOK_EXECUTION_FAILED: _h_ai_core.HaiErrorDef;
135
+ readonly LOG_PERSIST_FAILED: _h_ai_core.HaiErrorDef;
54
136
  };
55
- /** 任务参数字典(键值对) */
137
+ /**
138
+ * 任务参数字典(键值对)
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * import type { TaskParams } from '@h-ai/scheduler'
143
+ *
144
+ * const params: TaskParams = { month: '2026-10', dryRun: true }
145
+ * const month = params.month
146
+ * ```
147
+ */
56
148
  type TaskParams = Record<string, unknown>;
57
- /** 任务触发类型 */
149
+ /**
150
+ * 任务触发类型
151
+ *
152
+ * @example
153
+ * ```ts
154
+ * import type { TaskTriggerType } from '@h-ai/scheduler'
155
+ *
156
+ * const triggerType: TaskTriggerType = 'manual'
157
+ * const isManual = triggerType === 'manual'
158
+ * ```
159
+ */
58
160
  type TaskTriggerType = 'scheduled' | 'manual';
59
- /** 任务处理器类型 */
161
+ /**
162
+ * 任务处理器类型
163
+ *
164
+ * @example
165
+ * ```ts
166
+ * import type { TaskHandlerKind } from '@h-ai/scheduler'
167
+ *
168
+ * const kind: TaskHandlerKind = 'api'
169
+ * const needsNetwork = kind === 'api'
170
+ * ```
171
+ */
60
172
  type TaskHandlerKind = 'api' | 'js';
61
- /** 失败重试策略 */
173
+ /**
174
+ * 失败重试策略
175
+ *
176
+ * @example
177
+ * ```ts
178
+ * import type { TaskRetryPolicy } from '@h-ai/scheduler'
179
+ *
180
+ * const retry: TaskRetryPolicy = { maxAttempts: 3, backoffMs: [1000, 5000] }
181
+ * // 只有外部副作用确实按 occurrenceId 持久去重时,任务才能声明 idempotent。
182
+ * ```
183
+ */
62
184
  interface TaskRetryPolicy {
63
- /** 最大尝试次数(包含首次执行,最小 1) */
185
+ /** 最大尝试次数(含首次及崩溃恢复,范围 1–100,默认 1)。 */
64
186
  maxAttempts: number;
65
187
  /** 每次重试前的退避时间(毫秒);按顺序对应第 2、3... 次尝试 */
66
188
  backoffMs?: number[];
67
189
  }
68
- /** 任务执行目标类型 */
190
+ /**
191
+ * 任务执行目标类型
192
+ *
193
+ * @example
194
+ * ```ts
195
+ * import type { TaskExecutionTargetType } from '@h-ai/scheduler'
196
+ *
197
+ * const target: TaskExecutionTargetType = 'hook'
198
+ * const usesHostCallback = target === 'hook'
199
+ * ```
200
+ */
69
201
  type TaskExecutionTargetType = TaskHandlerKind | 'hook';
70
202
  /**
71
203
  * API 任务配置
204
+ *
205
+ * @example
206
+ * ```ts
207
+ * import type { ApiTaskConfig } from '@h-ai/scheduler'
208
+ *
209
+ * const handler: ApiTaskConfig = { kind: 'api', url: 'https://example.com/health', method: 'GET', timeout: 5000, maxResponseBytes: 4096 }
210
+ * // API 接收端若支持重试,须持久处理 Idempotency-Key 与 fencing 元数据。
211
+ * ```
72
212
  */
73
213
  interface ApiTaskConfig {
74
214
  /** 处理器类型 */
@@ -81,51 +221,61 @@ interface ApiTaskConfig {
81
221
  headers?: Record<string, string>;
82
222
  /** 请求体(POST/PUT/PATCH 时使用) */
83
223
  body?: unknown;
84
- /** 超时时间,单位毫秒(默认 30000) */
224
+ /** 请求及完整响应体读取的总超时,单位毫秒(默认 30000) */
85
225
  timeout?: number;
226
+ /** 响应体实际接收字节上限,必须为正安全整数(默认 1048576,即 1 MiB) */
227
+ maxResponseBytes?: number;
86
228
  }
87
229
  /**
88
230
  * JS 任务配置
89
231
  *
232
+ * ⚠️ 安全警示:`code` 仅允许受信任的服务端代码(例如仓库内常量或受控部署配置)。
233
+ * 当前实现通过 Node.js `vm` 便捷执行,不构成安全沙箱;禁止直接接收用户、租户或后台自由输入的 JS 字符串。
234
+ * 多租户或可配置任务优先使用 `kind: 'api'` 或 `hooks.onTaskExecute`。
235
+ *
90
236
  * `code` 为 JS 函数字符串,例如:
91
237
  * `(context) => ({ taskId: context.task.id, params: context.params })`
238
+ *
239
+ * @example
240
+ * ```ts
241
+ * import type { JsTaskConfig } from '@h-ai/scheduler'
242
+ *
243
+ * const handler: JsTaskConfig = { kind: 'js', code: '(context) => ({ taskId: context.taskId })', timeout: 1000 }
244
+ * // 仅装载受信任的服务端源码;工作线程不是不可信代码沙箱。
245
+ * ```
92
246
  */
93
247
  interface JsTaskConfig {
94
248
  /** 处理器类型 */
95
249
  kind: 'js';
96
- /** JS 函数字符串 */
250
+ /** JS 函数字符串(仅允许受信任的服务端代码,不是安全沙箱) */
97
251
  code: string;
98
- /** 软超时时间,单位毫秒 */
252
+ /** 独立线程执行期限,单位毫秒(默认 30000,含线程启动);超时终止线程后才允许重试 */
99
253
  timeout?: number;
100
254
  }
101
- /** 统一任务处理器配置 */
255
+ /**
256
+ * 统一任务处理器配置
257
+ *
258
+ * @example
259
+ * ```ts
260
+ * import type { TaskHandlerConfig } from '@h-ai/scheduler'
261
+ *
262
+ * const handler: TaskHandlerConfig = { kind: 'api', url: 'https://example.com/health' }
263
+ * const timeout = handler.timeout ?? 30000
264
+ * ```
265
+ */
102
266
  type TaskHandlerConfig = ApiTaskConfig | JsTaskConfig;
103
267
  /**
104
268
  * 任务定义
105
269
  *
106
270
  * @example
107
271
  * ```ts
108
- * const jsTask: TaskDefinition = {
109
- * id: 'cleanup',
110
- * name: '清理过期数据',
111
- * cron: '0 2 * * *',
112
- * params: { channel: 'nightly' },
113
- * handler: {
114
- * kind: 'js',
115
- * code: '(context) => ({ taskId: context.task.id, params: context.params })',
116
- * },
117
- * }
272
+ * import type { TaskDefinition } from '@h-ai/scheduler'
273
+ * import { scheduler } from '@h-ai/scheduler'
118
274
  *
119
- * const apiTask: TaskDefinition = {
120
- * id: 'health-check',
121
- * name: '健康检查',
122
- * cron: '&#42;/5 * * * *',
123
- * handler: {
124
- * kind: 'api',
125
- * url: 'https://api.example.com/health',
126
- * method: 'GET',
127
- * },
128
- * }
275
+ * // 宿主已成功初始化共享 reldb 与 scheduler。
276
+ * const definition: TaskDefinition = { ...{ id: 'daily-report', name: '每日报表', cron: '0 2 * * *', timezone: 'UTC' }, handler: { kind: 'api', url: 'https://example.com/health', maxResponseBytes: 4096 } }
277
+ * const registered = await scheduler.register(definition)
278
+ * if (!registered.success) throw new Error(registered.error.message)
129
279
  * ```
130
280
  */
131
281
  interface TaskDefinition {
@@ -137,12 +287,16 @@ interface TaskDefinition {
137
287
  description?: string;
138
288
  /** cron 表达式(标准 5 字段:分 时 日 月 周) */
139
289
  cron: string;
290
+ /** IANA 时区,用于解释 cron 墙上时间;省略或清空时统一使用 UTC,不读取节点 TZ。 */
291
+ timezone?: string;
140
292
  /** 是否启用(默认 true) */
141
293
  enabled?: boolean;
142
294
  /** 是否在执行后自动删除(默认 false) */
143
295
  deleteAfterRun?: boolean;
144
296
  /** 失败重试策略 */
145
297
  retry?: TaskRetryPolicy;
298
+ /** 全部副作用按 context.occurrenceId 原子持久去重时才为 true;默认 false,未知结果禁止自动重跑。 */
299
+ idempotent?: boolean;
146
300
  /** 通用参数 */
147
301
  params?: TaskParams;
148
302
  /** 任务处理器;为空时可由全局事件回调统一处理 */
@@ -150,6 +304,14 @@ interface TaskDefinition {
150
304
  }
151
305
  /**
152
306
  * 任务触发信息
307
+ *
308
+ * @example
309
+ * ```ts
310
+ * import type { TaskTriggerInfo } from '@h-ai/scheduler'
311
+ *
312
+ * const trigger: TaskTriggerInfo = { type: 'manual', source: 'billing-console' }
313
+ * const source = trigger.source ?? 'cron'
314
+ * ```
153
315
  */
154
316
  interface TaskTriggerInfo {
155
317
  /** 触发类型 */
@@ -159,8 +321,27 @@ interface TaskTriggerInfo {
159
321
  }
160
322
  /**
161
323
  * 任务执行上下文
324
+ *
325
+ * @example
326
+ * ```ts
327
+ * import type { SchedulerTaskContext } from '@h-ai/scheduler'
328
+ *
329
+ * function safeReceipt(context: SchedulerTaskContext): string {
330
+ * if (!context.occurrenceId || !context.executionToken) throw new Error('Shared execution identity required')
331
+ * return context.occurrenceId
332
+ * }
333
+ * // 接收端将稳定 receipt 原子持久去重;executionToken 不写入用户可见日志。
334
+ * ```
162
335
  */
163
336
  interface SchedulerTaskContext {
337
+ /** 一次调度发生的稳定标识;所有重试共享,供宿主构造业务幂等键。 */
338
+ occurrenceId?: string;
339
+ /** 当前领取独有的凭据,用于宿主条件提交;续租失败后不能继续产生副作用。 */
340
+ executionToken?: string;
341
+ /** 数据库执行序号;与 attempt 组成接收端可比较的 fencing 版本。 */
342
+ sequence?: number;
343
+ /** 同一 occurrence 中持久化的尝试次数。 */
344
+ attempt?: number;
164
345
  /** 当前任务 */
165
346
  task: TaskDefinition;
166
347
  /** 任务 ID */
@@ -170,10 +351,37 @@ interface SchedulerTaskContext {
170
351
  /** 触发信息 */
171
352
  trigger: TaskTriggerInfo;
172
353
  }
173
- /** 编译后的 JS 任务函数 */
174
- type JsTaskHandler = (context: SchedulerTaskContext) => unknown | Promise<unknown>;
175
- /** 任务开始事件 */
354
+ /**
355
+ * 编译后的 JS 任务函数
356
+ *
357
+ * @example
358
+ * ```ts
359
+ * import type { JsTaskHandler } from '@h-ai/scheduler'
360
+ *
361
+ * const handler: JsTaskHandler = (context, signal) => {
362
+ * signal?.throwIfAborted()
363
+ * return { taskId: context.taskId, batch: context.params.batch }
364
+ * }
365
+ * ```
366
+ */
367
+ type JsTaskHandler = (context: SchedulerTaskContext, signal?: AbortSignal) => unknown | Promise<unknown>;
368
+ /**
369
+ * 任务开始事件
370
+ *
371
+ * @example
372
+ * ```ts
373
+ * import type { SchedulerTaskStartEvent } from '@h-ai/scheduler'
374
+ *
375
+ * function summarizeStart(event: SchedulerTaskStartEvent) {
376
+ * return { taskId: event.task.id, occurrenceId: event.context?.occurrenceId, observedAt: event.startedAt }
377
+ * }
378
+ * ```
379
+ */
176
380
  interface SchedulerTaskStartEvent {
381
+ /** 已领取执行的持久身份,观测回调也可据此标记或幂等处理;竞争中断时不存在。 */
382
+ context?: SchedulerTaskContext;
383
+ /** 关闭调度器时取消;回调必须停止后续副作用并释放资源 */
384
+ signal: AbortSignal;
177
385
  /** 当前任务 */
178
386
  task: TaskDefinition;
179
387
  /** 触发信息 */
@@ -181,19 +389,55 @@ interface SchedulerTaskStartEvent {
181
389
  /** 开始时间(Unix 时间戳,毫秒) */
182
390
  startedAt: number;
183
391
  }
184
- /** 任务执行事件 */
392
+ /**
393
+ * 任务执行事件
394
+ *
395
+ * @example
396
+ * ```ts
397
+ * import type { SchedulerTaskExecuteEvent } from '@h-ai/scheduler'
398
+ *
399
+ * function execute(event: SchedulerTaskExecuteEvent) {
400
+ * event.signal.throwIfAborted()
401
+ * return { taskId: event.context.taskId, params: event.context.params }
402
+ * }
403
+ * ```
404
+ */
185
405
  interface SchedulerTaskExecuteEvent extends SchedulerTaskStartEvent {
186
406
  /** 执行上下文 */
187
407
  context: SchedulerTaskContext;
188
408
  }
189
- /** 任务中断事件 */
409
+ /**
410
+ * 任务中断事件
411
+ *
412
+ * @example
413
+ * ```ts
414
+ * import type { SchedulerTaskInterruptedEvent } from '@h-ai/scheduler'
415
+ *
416
+ * function summarizeInterruption(event: SchedulerTaskInterruptedEvent) {
417
+ * return { taskId: event.task.id, reason: event.reason, observedAt: event.interruptedAt }
418
+ * }
419
+ * // 中断观测不能证明外部副作用不存在。
420
+ * ```
421
+ */
190
422
  interface SchedulerTaskInterruptedEvent extends SchedulerTaskStartEvent {
191
423
  /** 中断时间(Unix 时间戳,毫秒) */
192
424
  interruptedAt: number;
193
425
  /** 中断原因 */
194
426
  reason: string;
195
427
  }
196
- /** 任务结束事件 */
428
+ /**
429
+ * 任务结束事件
430
+ *
431
+ * @example
432
+ * ```ts
433
+ * import type { SchedulerTaskFinishEvent } from '@h-ai/scheduler'
434
+ *
435
+ * function needsLogRepair(event: SchedulerTaskFinishEvent): boolean {
436
+ * return event.log.persistence.status === 'pending'
437
+ * }
438
+ * // 结束回调是观测;业务是否已提交以 journal 为准。
439
+ * ```
440
+ */
197
441
  interface SchedulerTaskFinishEvent extends SchedulerTaskStartEvent {
198
442
  /** 结束时间(Unix 时间戳,毫秒) */
199
443
  finishedAt: number;
@@ -205,6 +449,19 @@ interface SchedulerTaskFinishEvent extends SchedulerTaskStartEvent {
205
449
  *
206
450
  * - `onTaskExecute` 可用于统一处理无内置 handler 的任务
207
451
  * - `onTaskStart` / `onTaskInterrupted` / `onTaskFinish` 用于观测生命周期
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * import type { SchedulerTaskHooks } from '@h-ai/scheduler'
456
+ *
457
+ * const hooks: SchedulerTaskHooks = {
458
+ * onTaskExecute: ({ context, signal }) => {
459
+ * signal.throwIfAborted()
460
+ * return { taskId: context.taskId }
461
+ * },
462
+ * }
463
+ * // 有副作用的宿主需使用 context.occurrenceId 和持久条件写入。
464
+ * ```
208
465
  */
209
466
  interface SchedulerTaskHooks {
210
467
  /** 任务开始前触发 */
@@ -216,14 +473,60 @@ interface SchedulerTaskHooks {
216
473
  /** 任务结束时触发 */
217
474
  onTaskFinish?: (event: SchedulerTaskFinishEvent) => void | Promise<void>;
218
475
  }
219
- /** 执行状态 */
220
- type ExecutionStatus = 'success' | 'failed' | 'interrupted';
476
+ /**
477
+ * 执行状态
478
+ *
479
+ * @example
480
+ * ```ts
481
+ * import type { ExecutionStatus } from '@h-ai/scheduler'
482
+ *
483
+ * function needsReconciliation(status: ExecutionStatus): boolean {
484
+ * return status === 'unknown'
485
+ * }
486
+ * // unknown 先隔离旧执行并核对外部效果,不换键重试。
487
+ * ```
488
+ */
489
+ type ExecutionStatus = 'success' | 'failed' | 'interrupted' | 'unknown';
490
+ /**
491
+ * 日志投影状态,与业务 status 独立;unconfirmed 表示没有可补写的已确认终态。
492
+ *
493
+ * @example
494
+ * ```ts
495
+ * import type { TaskLogPersistence } from '@h-ai/scheduler'
496
+ *
497
+ * const persistence: TaskLogPersistence = { status: 'pending', error: { code: 'hai:scheduler:032', message: 'Log projection pending' } }
498
+ * const needsRepair = persistence.status === 'pending'
499
+ * ```
500
+ */
501
+ interface TaskLogPersistence {
502
+ /** pending 可由已发布 journal 补写;persisted 已确认日志和回执;unconfirmed 不能推断业务结果。 */
503
+ status: 'pending' | 'persisted' | 'unconfirmed';
504
+ /** 安全的公开错误,不包含 SQL、驱动 cause 或连接参数。 */
505
+ error?: {
506
+ code: string;
507
+ message: string;
508
+ };
509
+ }
221
510
  /**
222
511
  * 任务执行日志
512
+ *
513
+ * @example
514
+ * ```ts
515
+ * import type { TaskExecutionLog } from '@h-ai/scheduler'
516
+ *
517
+ * function summarize(log: TaskExecutionLog) {
518
+ * return { businessStatus: log.status, logStatus: log.persistence.status, occurrenceId: log.occurrenceId }
519
+ * }
520
+ * // pending 的成功业务只补写日志,不重跑处理器。
521
+ * ```
223
522
  */
224
523
  interface TaskExecutionLog {
225
- /** 日志 ID */
226
- id: number;
524
+ /** 持久执行回执;相同定时 occurrence 或手动幂等键共用。 */
525
+ occurrenceId?: string;
526
+ /** 每次尝试固定的 UUID 主键;未知写入回执或并发补写均复用。 */
527
+ id: string;
528
+ /** 独立持久化状态;业务成功不等于日志保存成功。 */
529
+ persistence: TaskLogPersistence;
227
530
  /** 任务 ID */
228
531
  taskId: string;
229
532
  /** 任务名称 */
@@ -236,7 +539,7 @@ interface TaskExecutionLog {
236
539
  triggerSource: string | null;
237
540
  /** 执行状态 */
238
541
  status: ExecutionStatus;
239
- /** 执行结果(JSON 字符串) */
542
+ /** 序列化 JS/Hook 结果或 API 响应正文;无结果为 null */
240
543
  result: string | null;
241
544
  /** 错误或中断信息 */
242
545
  error: string | null;
@@ -249,6 +552,17 @@ interface TaskExecutionLog {
249
552
  }
250
553
  /**
251
554
  * 执行日志查询选项
555
+ *
556
+ * @example
557
+ * ```ts
558
+ * import type { LogQueryOptions } from '@h-ai/scheduler'
559
+ * import { scheduler } from '@h-ai/scheduler'
560
+ *
561
+ * const options: LogQueryOptions = { taskId: 'daily-report', status: 'success', pagination: { page: 1, pageSize: 20 } }
562
+ * const logs = await scheduler.getLogs(options)
563
+ * if (!logs.success) throw new Error(logs.error.message)
564
+ * const page = logs.data.items
565
+ * ```
252
566
  */
253
567
  interface LogQueryOptions {
254
568
  /** 按任务 ID 过滤 */
@@ -266,7 +580,17 @@ interface LogQueryOptions {
266
580
  /** 分页参数(page 从 1 开始,pageSize 默认 20) */
267
581
  pagination?: PaginationOptionsInput;
268
582
  }
269
- /** 日志清理策略 */
583
+ /**
584
+ * 日志清理策略
585
+ *
586
+ * @example
587
+ * ```ts
588
+ * import type { SchedulerLogCleanupPolicy } from '@h-ai/scheduler'
589
+ *
590
+ * const policy: SchedulerLogCleanupPolicy = { maxLogs: 1000, retentionDays: 30 }
591
+ * // 仅清理日志投影,不撤销或重排共享 execution journal。
592
+ * ```
593
+ */
270
594
  interface SchedulerLogCleanupPolicy {
271
595
  /** 最多保留日志条数 */
272
596
  maxLogs?: number;
@@ -278,14 +602,29 @@ interface SchedulerLogCleanupPolicy {
278
602
  *
279
603
  * 可更新的字段包括:名称、cron 表达式、启用状态、参数、处理器。
280
604
  * 任务 ID 不可更新。
605
+ *
606
+ * @example
607
+ * ```ts
608
+ * import type { TaskUpdateInput } from '@h-ai/scheduler'
609
+ * import { scheduler } from '@h-ai/scheduler'
610
+ *
611
+ * const updates: TaskUpdateInput = { enabled: false, timezone: null }
612
+ * const changed = await scheduler.updateTask('daily-report', updates)
613
+ * if (!changed.success) throw new Error(changed.error.message)
614
+ * // null 时区恢复 UTC,任务 ID 不能修改。
615
+ * ```
281
616
  */
282
617
  interface TaskUpdateInput {
618
+ /** 全部副作用的持久去重能力声明。 */
619
+ idempotent?: boolean;
283
620
  /** 任务名称 */
284
621
  name?: string;
285
622
  /** 任务描述 */
286
623
  description?: string;
287
624
  /** cron 表达式 */
288
625
  cron?: string;
626
+ /** IANA 时区;传 null 表示清空并恢复 UTC,不读取节点 TZ。 */
627
+ timezone?: string | null;
289
628
  /** 是否启用 */
290
629
  enabled?: boolean;
291
630
  /** 是否在执行后自动删除 */
@@ -297,15 +636,122 @@ interface TaskUpdateInput {
297
636
  /** 任务处理器;传 null 表示清空内置处理器 */
298
637
  handler?: TaskHandlerConfig | null;
299
638
  }
300
- /** 手工触发输入 */
639
+ /**
640
+ * 手工触发输入
641
+ *
642
+ * @example
643
+ * ```ts
644
+ * import type { TriggerTaskInput } from '@h-ai/scheduler'
645
+ * import { scheduler } from '@h-ai/scheduler'
646
+ *
647
+ * const options: TriggerTaskInput = { source: 'billing-console', idempotencyKey: 'billing-2026-10' }
648
+ * const result = await scheduler.trigger('daily-report', options)
649
+ * if (!result.success) throw new Error(result.error.message)
650
+ * const status = result.data.status
651
+ * ```
652
+ */
301
653
  interface TriggerTaskInput {
302
654
  /** 手工触发来源(例如 admin-console / api / cli) */
303
655
  source?: string;
656
+ /** 稳定业务触发键(1–128 字符);同任务重复使用会命中同一持久执行。 */
657
+ idempotencyKey?: string;
658
+ }
659
+ /**
660
+ * 可信运维可见的执行状态;unknown 继续占用任务串行槽。
661
+ *
662
+ * @example
663
+ * ```ts
664
+ * import type { SchedulerExecutionState } from '@h-ai/scheduler'
665
+ *
666
+ * function occupiesUncertainSlot(state: SchedulerExecutionState): boolean {
667
+ * return state === 'unknown'
668
+ * }
669
+ * ```
670
+ */
671
+ type SchedulerExecutionState = 'claimed' | 'running' | ExecutionStatus | 'discarded';
672
+ /**
673
+ * 不包含代码、参数、URL 或 owner 凭据的共享执行记录。
674
+ *
675
+ * @example
676
+ * ```ts
677
+ * import type { SchedulerExecutionEntry } from '@h-ai/scheduler'
678
+ *
679
+ * function publicAudit(entry: SchedulerExecutionEntry) {
680
+ * return { occurrenceId: entry.occurrenceId, status: entry.status, revision: entry.updatedAt }
681
+ * }
682
+ * // 安全投影不包含 owner token 和业务载荷。
683
+ * ```
684
+ */
685
+ interface SchedulerExecutionEntry {
686
+ /** 稳定执行回执。 */
687
+ occurrenceId: string;
688
+ /** 任务标识。 */
689
+ taskId: string;
690
+ /** 共享状态。 */
691
+ status: SchedulerExecutionState;
692
+ /** 数据库序号,配合 attempt 用于外部 fencing。 */
693
+ sequence: number;
694
+ /** 已开始的尝试次数。 */
695
+ attemptCount: number;
696
+ /** 最近状态版本(Unix 毫秒),用于人工裁定条件。 */
697
+ updatedAt: number;
698
+ /** 日志投影独立状态;pending 不会重新排队业务。 */
699
+ logPersistence: TaskLogPersistence['status'];
700
+ }
701
+ /**
702
+ * 可信服务端的执行查询与人工核对入口。
703
+ *
704
+ * @example
705
+ * ```ts
706
+ * import type { SchedulerExecutionOperations } from '@h-ai/scheduler'
707
+ *
708
+ * async function repairPending(execution: SchedulerExecutionOperations) {
709
+ * const pending = await execution.listLogFailures({ limit: 20 })
710
+ * if (!pending.success) return pending
711
+ * for (const entry of pending.data) {
712
+ * const repaired = await execution.repairLog(entry.occurrenceId)
713
+ * if (!repaired.success) return repaired
714
+ * }
715
+ * }
716
+ * // 此链路不会调用业务 handler。
717
+ * ```
718
+ */
719
+ interface SchedulerExecutionOperations {
720
+ /** 按回执查询安全元数据。@example await scheduler.execution.get(occurrenceId) */
721
+ get: (occurrenceId: string) => Promise<HaiResult<SchedulerExecutionEntry | null>>;
722
+ /** 有界查询待核对的 unknown;每页 1–100 条。@example await scheduler.execution.listUnknown({ limit: 50, offset: 0 }) */
723
+ listUnknown: (options?: {
724
+ limit?: number;
725
+ offset?: number;
726
+ }) => Promise<HaiResult<SchedulerExecutionEntry[]>>;
727
+ /** 分页查询已有终态但日志尚待补写的回执,不含业务载荷。@example await scheduler.execution.listLogFailures({ limit: 50 }) */
728
+ listLogFailures: (options?: {
729
+ limit?: number;
730
+ offset?: number;
731
+ }) => Promise<HaiResult<SchedulerExecutionEntry[]>>;
732
+ /** 只从已发布 journal 幂等补写日志,不执行业务;并发调用安全。@example await scheduler.execution.repairLog(occurrenceId) */
733
+ repairLog: (occurrenceId: string) => Promise<HaiResult<void>>;
734
+ /** 先终止旧 runner 并核对外部结果,再条件裁定;不能重新排队。@example await scheduler.execution.resolveUnknown(id, { status: 'discarded', expectedUpdatedAt: entry.updatedAt }) */
735
+ resolveUnknown: (occurrenceId: string, resolution: {
736
+ status: 'success' | 'discarded';
737
+ expectedUpdatedAt: number;
738
+ }) => Promise<HaiResult<void>>;
304
739
  }
305
740
  /**
306
741
  * 调度器初始化输入
307
742
  *
308
743
  * 包含调度器配置、可选的预定义任务列表,以及可选的全局生命周期回调。
744
+ *
745
+ * @example
746
+ * ```ts
747
+ * import type { SchedulerInitInput } from '@h-ai/scheduler'
748
+ * import { scheduler } from '@h-ai/scheduler'
749
+ *
750
+ * // 宿主已成功初始化共享 reldb。
751
+ * const input: SchedulerInitInput = { leaseMs: 60000, tasks: [{ id: 'daily-report', name: '每日报表', cron: '0 2 * * *', timezone: 'UTC' }], hooks: { onTaskExecute: ({ context }) => ({ taskId: context.taskId }) } }
752
+ * const initialized = await scheduler.init(input)
753
+ * if (!initialized.success) throw new Error(initialized.error.message)
754
+ * ```
309
755
  */
310
756
  interface SchedulerInitInput extends SchedulerConfigInput {
311
757
  /** 预定义任务列表(从配置中加载,初始化时自动注册) */
@@ -315,8 +761,24 @@ interface SchedulerInitInput extends SchedulerConfigInput {
315
761
  }
316
762
  /**
317
763
  * 调度器函数接口
764
+ *
765
+ * @example
766
+ * ```ts
767
+ * import type { SchedulerFunctions } from '@h-ai/scheduler'
768
+ *
769
+ * async function stopScheduler(instance: SchedulerFunctions) {
770
+ * const stopped = instance.stop()
771
+ * if (!stopped.success) return stopped
772
+ * await instance.close()
773
+ * }
774
+ * // close 返回 Promise<void>,宿主随后关闭自己拥有的共享数据库。
775
+ * ```
318
776
  */
319
777
  interface SchedulerFunctions {
778
+ /** 共享执行状态、未知结果查询与可信人工裁定。 */
779
+ readonly execution: SchedulerExecutionOperations;
780
+ /** 刷新共享数据库中的任务定义,用于跨实例配置读取。 */
781
+ refreshTasks: () => Promise<HaiResult<void>>;
320
782
  /** 初始化调度器 */
321
783
  init: (config?: SchedulerInitInput) => Promise<HaiResult<void>>;
322
784
  /** 注册任务 */
@@ -359,6 +821,50 @@ interface SchedulerFunctions {
359
821
  * @module scheduler-main
360
822
  */
361
823
 
824
+ /**
825
+ * 定时任务公共入口;先初始化共享 RelDB,再注册/触发/启动;关闭会排空任务和日志修复,宿主最后关闭数据库。
826
+ *
827
+ * @example
828
+ * ```ts
829
+ * import { core } from '@h-ai/core'
830
+ * import { reldb } from '@h-ai/reldb'
831
+ * import { scheduler } from '@h-ai/scheduler'
832
+ *
833
+ * // 本地开发示例;生产使用所有节点共同连接的 PostgreSQL/MySQL。
834
+ * const database = await reldb.init({ type: 'sqlite', database: ':memory:' })
835
+ * if (!database.success) throw new Error(database.error.message)
836
+ * try {
837
+ * const initialized = await scheduler.init({ hooks: { onTaskExecute: ({ context }) => ({ taskId: context.taskId }) } })
838
+ * if (!initialized.success) throw new Error(initialized.error.message)
839
+ * const registered = await scheduler.register({ id: 'daily-report', name: '每日报表', cron: '0 2 * * *', timezone: 'UTC' })
840
+ * if (!registered.success) throw new Error(registered.error.message)
841
+ * const executed = await scheduler.trigger('daily-report', { idempotencyKey: 'report-2026-10-23' })
842
+ * if (!executed.success) throw new Error(executed.error.message)
843
+ * // 业务 status 与 persistence 分开判断;pending 只补日志,不重跑业务。
844
+ * const status = executed.data.status
845
+ * const persistence = executed.data.persistence.status
846
+ * } finally {
847
+ * await scheduler.close()
848
+ * const closed = await reldb.close()
849
+ * if (!closed.success) {
850
+ * core.logger.error('Database cleanup failed', { errorCode: closed.error.code })
851
+ * process.exitCode = 1
852
+ * }
853
+ * }
854
+ * ```
855
+ */
362
856
  declare const scheduler: SchedulerFunctions;
363
857
 
364
- export { type ApiTaskConfig, type ExecutionStatus, HaiSchedulerError, type JsTaskConfig, type JsTaskHandler, type LogQueryOptions, type SchedulerConfig, type SchedulerConfigInput, SchedulerConfigSchema, type SchedulerFunctions, type SchedulerInitInput, type SchedulerLogCleanupPolicy, type SchedulerTaskContext, type SchedulerTaskExecuteEvent, type SchedulerTaskFinishEvent, type SchedulerTaskHooks, type SchedulerTaskInterruptedEvent, type SchedulerTaskStartEvent, type TaskDefinition, type TaskExecutionLog, type TaskExecutionTargetType, type TaskHandlerConfig, type TaskHandlerKind, type TaskParams, type TaskRetryPolicy, type TaskTriggerInfo, type TaskTriggerType, type TaskUpdateInput, type TriggerTaskInput, scheduler };
858
+ /**
859
+ * 预检或升级调度器表;旧日志归档并幂等复制,新版执行账本与旧历史隔离。
860
+ * @example
861
+ * ```ts
862
+ * import { migrateScheduler } from '@h-ai/scheduler'
863
+ * const plan = await migrateScheduler({ dryRun: true })
864
+ * ```
865
+ */
866
+ declare function migrateScheduler(options?: {
867
+ dryRun?: boolean;
868
+ }): Promise<_h_ai_core.HaiResult<_h_ai_reldb.SchemaMigrationPlan>>;
869
+
870
+ export { type ApiTaskConfig, ExecutionResolutionSchema, type ExecutionStatus, HaiSchedulerError, type JsTaskConfig, type JsTaskHandler, type LogQueryOptions, type SchedulerConfig, type SchedulerConfigInput, SchedulerConfigSchema, type SchedulerExecutionEntry, type SchedulerExecutionOperations, type SchedulerExecutionState, type SchedulerFunctions, type SchedulerInitInput, type SchedulerLogCleanupPolicy, type SchedulerTaskContext, type SchedulerTaskExecuteEvent, type SchedulerTaskFinishEvent, type SchedulerTaskHooks, type SchedulerTaskInterruptedEvent, type SchedulerTaskStartEvent, type TaskDefinition, type TaskExecutionLog, type TaskExecutionTargetType, type TaskHandlerConfig, type TaskHandlerKind, type TaskLogPersistence, type TaskParams, type TaskRetryPolicy, type TaskTriggerInfo, type TaskTriggerType, type TaskUpdateInput, type TriggerTaskInput, TriggerTaskSchema, migrateScheduler, scheduler };