@h-ai/scheduler 1.0.0-beta.2 → 1.0.0-beta.21
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/README.en.md +94 -39
- package/README.ja.md +93 -38
- package/README.md +93 -38
- package/dist/index.d.ts +2 -1
- package/dist/index.js +805 -200
- package/dist/index.js.map +1 -1
- package/dist/scheduler-js-worker.d.ts +6 -1
- package/dist/scheduler-js-worker.js +4 -1
- package/dist/scheduler-js-worker.js.map +1 -1
- package/package.json +10 -10
package/README.en.md
CHANGED
|
@@ -4,24 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
[Framework home](../../README.en.md) · Related modules: [@h-ai/core](../core/README.en.md) · [@h-ai/reldb](../reldb/README.en.md)
|
|
6
6
|
|
|
7
|
-
## Introduction
|
|
8
|
-
|
|
9
7
|
A scheduled task module with a unified task model, cron scheduling, JS function strings / HTTP API execution, persistence, execution log queries, and global task lifecycle hooks.
|
|
10
8
|
|
|
11
|
-
##
|
|
12
|
-
|
|
13
|
-
- Run tasks on a cron schedule or trigger them from application code.
|
|
14
|
-
- Execute HTTP requests, trusted JavaScript and application hooks, with retry and cancellation.
|
|
15
|
-
- Persist tasks, execution journals and renewable leases in a shared database, with unknown-outcome isolation.
|
|
16
|
-
|
|
17
|
-
## Getting started
|
|
9
|
+
## Quick Start
|
|
18
10
|
|
|
19
11
|
### Dependencies
|
|
20
12
|
|
|
21
13
|
- `@h-ai/reldb`: initialize the shared database first; tasks, execution journals and leases are mandatory, and `enableDb` accepts only true.
|
|
22
14
|
|
|
23
|
-
### Quick start
|
|
24
|
-
|
|
25
15
|
```ts
|
|
26
16
|
import { reldb } from '@h-ai/reldb'
|
|
27
17
|
import { scheduler } from '@h-ai/scheduler'
|
|
@@ -79,6 +69,59 @@ scheduler.stop()
|
|
|
79
69
|
await scheduler.close()
|
|
80
70
|
```
|
|
81
71
|
|
|
72
|
+
## Features
|
|
73
|
+
|
|
74
|
+
- Run tasks on a cron schedule or trigger them from application code.
|
|
75
|
+
- Execute HTTP requests, trusted JavaScript and application hooks, with retry and cancellation.
|
|
76
|
+
- Persist tasks, execution journals and renewable leases in a shared database, with unknown-outcome isolation.
|
|
77
|
+
|
|
78
|
+
### Operations and results
|
|
79
|
+
|
|
80
|
+
Use the complete initialization flow in this section first. The host validates and authorizes example business values; check success before reading data from asynchronous domain results. Here void means completion without data, null means absent; synchronous factories/tools return the listed type directly.
|
|
81
|
+
|
|
82
|
+
#### scheduler
|
|
83
|
+
|
|
84
|
+
Definitions take task, ID, ID+patch or no-arg refresh and yield void HaiResult. tasks is the last successful read-only snapshot, not authorization or live DB state.
|
|
85
|
+
|
|
86
|
+
| Entry | Input parameters | Successful result | Call example |
|
|
87
|
+
| ------------------------ | ---------------- | ----------------- | ---------------------------------------------------------------------------------------------- |
|
|
88
|
+
| `scheduler.register` | task | `void` | `await scheduler.register({ id: 'daily', name: 'Daily', cron: '0 2 * * *', timezone: 'UTC' })` |
|
|
89
|
+
| `scheduler.unregister` | taskId | `void` | `await scheduler.unregister('daily')` |
|
|
90
|
+
| `scheduler.updateTask` | taskId, updates | `void` | `await scheduler.updateTask('daily', { enabled: false })` |
|
|
91
|
+
| `scheduler.refreshTasks` | No arguments | `void` | `await scheduler.refreshTasks()` |
|
|
92
|
+
|
|
93
|
+
#### scheduler
|
|
94
|
+
|
|
95
|
+
start/stop return synchronous HaiResult; trigger takes task ID/params and yields an attempt log; getLogs filters/page yield a log page. Stop does not undo in-flight effects.
|
|
96
|
+
|
|
97
|
+
| Entry | Input parameters | Successful result | Call example |
|
|
98
|
+
| ------------------- | ---------------- | ----------------------------------- | ---------------------------------------------------- |
|
|
99
|
+
| `scheduler.start` | No arguments | `void` | `scheduler.start()` |
|
|
100
|
+
| `scheduler.stop` | No arguments | `void` | `scheduler.stop()` |
|
|
101
|
+
| `scheduler.trigger` | taskId, options | `TaskExecutionLog` | `await scheduler.trigger('daily')` |
|
|
102
|
+
| `scheduler.getLogs` | options | `PaginatedResult<TaskExecutionLog>` | `await scheduler.getLogs({ page: 1, pageSize: 20 })` |
|
|
103
|
+
|
|
104
|
+
#### scheduler
|
|
105
|
+
|
|
106
|
+
Install/clear business/event callbacks, returning synchronous HaiResult. Hooks must honor signal and external-effect idempotency.
|
|
107
|
+
|
|
108
|
+
| Entry | Input parameters | Successful result | Call example |
|
|
109
|
+
| ---------------------- | ---------------- | ----------------- | ------------------------------- |
|
|
110
|
+
| `scheduler.setHooks` | hooks | `void` | `scheduler.setHooks(taskHooks)` |
|
|
111
|
+
| `scheduler.clearHooks` | No arguments | `void` | `scheduler.clearHooks()` |
|
|
112
|
+
|
|
113
|
+
#### scheduler.execution
|
|
114
|
+
|
|
115
|
+
Authoritative journal: get occurrenceId yields entry/null, lists take limit/offset and yield arrays, repairLog ID idempotently repairs logs, resolveUnknown ID/decision/expectedUpdatedAt conditionally releases the slot and yields void.
|
|
116
|
+
|
|
117
|
+
| Entry | Input parameters | Successful result | Call example |
|
|
118
|
+
| ------------------------------------- | ------------------------ | --------------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
119
|
+
| `scheduler.execution.get` | occurrenceId | `SchedulerExecutionEntry \| null` | `await scheduler.execution.get(occurrenceId)` |
|
|
120
|
+
| `scheduler.execution.listUnknown` | options | `SchedulerExecutionEntry[]` | `await scheduler.execution.listUnknown({ limit: 20, offset: 0 })` |
|
|
121
|
+
| `scheduler.execution.listLogFailures` | options | `SchedulerExecutionEntry[]` | `await scheduler.execution.listLogFailures({ limit: 20, offset: 0 })` |
|
|
122
|
+
| `scheduler.execution.repairLog` | occurrenceId | `void` | `await scheduler.execution.repairLog(occurrenceId)` |
|
|
123
|
+
| `scheduler.execution.resolveUnknown` | occurrenceId, resolution | `void` | `await scheduler.execution.resolveUnknown(occurrenceId, { status: 'success', expectedUpdatedAt })` |
|
|
124
|
+
|
|
82
125
|
### Unified task model
|
|
83
126
|
|
|
84
127
|
```ts
|
|
@@ -184,36 +227,14 @@ Execution logs support automatic cleanup policies configured at initialization:
|
|
|
184
227
|
- `tasks` / `hooks` / `config` / `isInitialized` / `isRunning`
|
|
185
228
|
- `close()`
|
|
186
229
|
|
|
187
|
-
### Error handling
|
|
188
|
-
|
|
189
|
-
All public APIs except `close()` return `HaiResult<T>`.
|
|
190
|
-
|
|
191
|
-
Common error codes:
|
|
192
|
-
|
|
193
|
-
| Error code | code | Description |
|
|
194
|
-
| ----------------------------------------- | ------------------- | ----------------------------- |
|
|
195
|
-
| `HaiSchedulerError.NOT_INITIALIZED` | `hai:scheduler:010` | Not initialized |
|
|
196
|
-
| `HaiSchedulerError.INIT_FAILED` | `hai:scheduler:011` | Initialization failed |
|
|
197
|
-
| `HaiSchedulerError.CONFIG_ERROR` | `hai:scheduler:012` | Invalid configuration |
|
|
198
|
-
| `HaiSchedulerError.TASK_NOT_FOUND` | `hai:scheduler:020` | Task not found |
|
|
199
|
-
| `HaiSchedulerError.TASK_ALREADY_EXISTS` | `hai:scheduler:021` | Task already exists |
|
|
200
|
-
| `HaiSchedulerError.INVALID_CRON` | `hai:scheduler:022` | Invalid cron expression |
|
|
201
|
-
| `HaiSchedulerError.EXECUTION_FAILED` | `hai:scheduler:023` | Execution failed |
|
|
202
|
-
| `HaiSchedulerError.JS_EXECUTION_FAILED` | `hai:scheduler:024` | JS execution failed |
|
|
203
|
-
| `HaiSchedulerError.API_EXECUTION_FAILED` | `hai:scheduler:025` | API execution failed |
|
|
204
|
-
| `HaiSchedulerError.DB_SAVE_FAILED` | `hai:scheduler:026` | Database save failed |
|
|
205
|
-
| `HaiSchedulerError.ALREADY_RUNNING` | `hai:scheduler:027` | Already running |
|
|
206
|
-
| `HaiSchedulerError.NOT_RUNNING` | `hai:scheduler:028` | Not running |
|
|
207
|
-
| `HaiSchedulerError.JS_COMPILE_FAILED` | `hai:scheduler:030` | JS compilation failed |
|
|
208
|
-
| `HaiSchedulerError.HOOK_EXECUTION_FAILED` | `hai:scheduler:031` | Hook execution failed |
|
|
209
|
-
| `HaiSchedulerError.LOG_PERSIST_FAILED` | `hai:scheduler:032` | Log persistence not confirmed |
|
|
210
|
-
|
|
211
230
|
### Runtime behavior and limits
|
|
212
231
|
|
|
213
232
|
All nodes must initialize the same shared RelDB first (PostgreSQL/MySQL for production across hosts; SQLite only for local processes that correctly share the same file). Task definitions, execution journals, active task slots and leases are persisted; `enableDb` accepts only true. Cache is no longer required. `leaseMs` defaults to 300000 and accepts 1000–86400000 milliseconds, with renewal during execution. Cron, manual and later periods share one active task slot; an expired owner cannot revive or commit. Nodes refresh definitions every `tickInterval`; `tasks` is the last successful snapshot. Failed reads, deletion, disabling or rescheduling interrupt stale attempts, without rolling back external effects.
|
|
214
233
|
|
|
215
234
|
`context.occurrenceId` persists across retries and nodes for a cron minute. Manual triggers accept a 1–128 character `idempotencyKey` to reuse the same record, otherwise each is independent. `executionToken` changes per claim; `sequence` and `attempt` identify the execution generation. API jobs override `Idempotency-Key`, `X-Scheduler-Sequence`, `X-Scheduler-Attempt` and `X-Scheduler-Task` (percent-encoded task ID). Claimed lifecycle callbacks expose the same ID in `event.context`; any callback side effects also need deduplication.
|
|
216
235
|
|
|
236
|
+
On PostgreSQL, restarting within the same minute or claiming from multiple nodes can encounter an existing execution record or an occupied task slot. The scheduler handles these conflicts as normal contention. Use `scheduler.execution.get(occurrenceId)` to check the execution status and keep the journal and its unique constraints to prevent duplicate executions.
|
|
237
|
+
|
|
217
238
|
`idempotent` defaults to false. Set true only when the receiver atomically persists its deduplication ledger with every side effect. Expired running executions can be recovered with the same occurrenceId only under this declaration; non-idempotent jobs or executions that exhaust the stored retry.maxAttempts budget (default 1, range 1–100 including initial attempts and recovery) become `unknown` and retain the active task slot. A lease cannot revoke an external request already sent by a paused process; headers alone do not implement deduplication. Retries also follow this declaration.
|
|
218
239
|
|
|
219
240
|
Use `scheduler.execution.get(occurrenceId)` for authoritative state and `listUnknown({ limit, offset })` with limit 1–100 and offset 0–1000000. Trusted operators must confirm external effects and terminate the old runner before releasing its slot through `resolveUnknown(id, { status: 'success' | 'discarded', expectedUpdatedAt })`, which uses CAS. Never requeue unknown executions directly. `log.occurrenceId` is the receipt; `getLogs` contains observational attempt logs. Log retention does not delete the journal or idempotency history.
|
|
@@ -224,7 +245,7 @@ Repair shrinks the pending list. Drain batches repeatedly at offset=0 instead of
|
|
|
224
245
|
|
|
225
246
|
Trusted server operators monitor `execution.listLogFailures({ limit, offset })` with the same bounds as listUnknown and call `execution.repairLog(occurrenceId)` to replay logs from the shared journal across nodes, restarts, or concurrent calls. Stable primary keys and complete payload comparison handle committed writes with lost acknowledgements. `LOG_PERSIST_FAILED` (032) retains pending state and emits a safe warning. If the entire database is unavailable before the terminal commit, reconcile unknown effects; do not assume a recoverable outcome exists. Repair and retention never call business hooks. Retention failure only warns. `onTaskFinish` reports local business completion with unconfirmed persistence; use the trigger result and execution.get.logPersistence for confirmation.
|
|
226
247
|
|
|
227
|
-
Pre-claim interrupted events are observational logs without a committed outcome to repair; unacknowledged writes remain unconfirmed. JSON payloads preserve full results and all retries beyond MySQL's 255-character text mapping
|
|
248
|
+
Pre-claim interrupted events are observational logs without a committed outcome to repair; unacknowledged writes remain unconfirmed. JSON payloads preserve full results and all retries beyond MySQL's 255-character text mapping; execution ledgers remain separate. Closing waits for in-flight repairs; close scheduler before the database.
|
|
228
249
|
|
|
229
250
|
```ts
|
|
230
251
|
const result = await scheduler.trigger('cleanup', { idempotencyKey: 'cleanup-2026-10-23' })
|
|
@@ -254,13 +275,47 @@ Claim, begin, renewal, completion, expiration scans and isolation calculate/chec
|
|
|
254
275
|
|
|
255
276
|
When a scheduled task sends Reach notifications, a scheduler lock or task completion does not guarantee one external delivery. Follow [Reach queue semantics](../reach/README.en.md) with persistent queueId keys. HTTP receivers must atomically persist deduplication with their side effects. Review unknown in-flight SMTP/SMS outcomes manually; scheduler retries must not blindly send them again.
|
|
256
277
|
|
|
257
|
-
|
|
278
|
+
### Definition consistency and persistence setup
|
|
258
279
|
|
|
259
280
|
Definition refresh, registration, update and deletion are coordinated in arrival order within each process, including a mutation's refresh and commit. Valid concurrent registrations no longer fail merely because snapshots interleave; actual database failures still return errors. close stops entry points and the runner, cancels read waits and operations that have not started writing, then drains active persistent writes. Late snapshots cannot publish or repopulate state afterward. Business callbacks do not hold this queue. Nodes still rely on the shared database, versions and leases; local coordination is not a distributed lock.
|
|
260
281
|
|
|
261
|
-
After RelDB
|
|
282
|
+
After RelDB initialization, `migrateScheduler({ dryRun: true })` previews persistence preparation; scheduler.init performs supported setup before creating repositories. Back up and use an exclusive change window, stop startup on failure and keep the execution journal distinct from observation logs.
|
|
283
|
+
|
|
284
|
+
## Configuration
|
|
285
|
+
|
|
286
|
+
Lifecycle: init takes backend/business configuration; use the module only after success. Await close before releasing borrowed dependencies. Follow the quick-start example and public signatures for exact return values.
|
|
287
|
+
|
|
288
|
+
The host loads and validates configuration before passing it to this module. Keep secrets in private server environment files. Select the backend, capacity, deadlines and logging for the actual use case; reinitialize and check the result after changes.
|
|
289
|
+
|
|
290
|
+
[Per-option purpose, use cases and examples](../../docs/usage/configuration/operations.md).
|
|
291
|
+
|
|
292
|
+
## Error Handling
|
|
293
|
+
|
|
294
|
+
Check result.success for domain operations. Handle failures with the module error definitions and safe messages; retain codes, correlation IDs and sanitized causes in server logs. Synchronous tools, factories, stream iteration and lifecycle calls follow their own signatures. A completed Promise alone is not business success. See each feature for recovery limits.
|
|
295
|
+
|
|
296
|
+
All public APIs except `close()` return `HaiResult<T>`.
|
|
297
|
+
|
|
298
|
+
Common error codes:
|
|
299
|
+
|
|
300
|
+
| Error code | code | Description |
|
|
301
|
+
| ----------------------------------------- | ------------------- | ----------------------------- |
|
|
302
|
+
| `HaiSchedulerError.NOT_INITIALIZED` | `hai:scheduler:010` | Not initialized |
|
|
303
|
+
| `HaiSchedulerError.INIT_FAILED` | `hai:scheduler:011` | Initialization failed |
|
|
304
|
+
| `HaiSchedulerError.CONFIG_ERROR` | `hai:scheduler:012` | Invalid configuration |
|
|
305
|
+
| `HaiSchedulerError.TASK_NOT_FOUND` | `hai:scheduler:020` | Task not found |
|
|
306
|
+
| `HaiSchedulerError.TASK_ALREADY_EXISTS` | `hai:scheduler:021` | Task already exists |
|
|
307
|
+
| `HaiSchedulerError.INVALID_CRON` | `hai:scheduler:022` | Invalid cron expression |
|
|
308
|
+
| `HaiSchedulerError.EXECUTION_FAILED` | `hai:scheduler:023` | Execution failed |
|
|
309
|
+
| `HaiSchedulerError.JS_EXECUTION_FAILED` | `hai:scheduler:024` | JS execution failed |
|
|
310
|
+
| `HaiSchedulerError.API_EXECUTION_FAILED` | `hai:scheduler:025` | API execution failed |
|
|
311
|
+
| `HaiSchedulerError.DB_SAVE_FAILED` | `hai:scheduler:026` | Database save failed |
|
|
312
|
+
| `HaiSchedulerError.ALREADY_RUNNING` | `hai:scheduler:027` | Already running |
|
|
313
|
+
| `HaiSchedulerError.NOT_RUNNING` | `hai:scheduler:028` | Not running |
|
|
314
|
+
| `HaiSchedulerError.JS_COMPILE_FAILED` | `hai:scheduler:030` | JS compilation failed |
|
|
315
|
+
| `HaiSchedulerError.HOOK_EXECUTION_FAILED` | `hai:scheduler:031` | Hook execution failed |
|
|
316
|
+
| `HaiSchedulerError.LOG_PERSIST_FAILED` | `hai:scheduler:032` | Log persistence not confirmed |
|
|
262
317
|
|
|
263
|
-
## Development
|
|
318
|
+
## Development
|
|
264
319
|
|
|
265
320
|
```bash
|
|
266
321
|
pnpm --filter @h-ai/scheduler test
|
package/README.ja.md
CHANGED
|
@@ -4,24 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
[フレームワークのホーム](../../README.ja.md) · 関連モジュール:[@h-ai/core](../core/README.ja.md) · [@h-ai/reldb](../reldb/README.ja.md)
|
|
6
6
|
|
|
7
|
-
## 概要
|
|
8
|
-
|
|
9
7
|
共通のタスクモデル、cron スケジュール、JS 関数文字列・HTTP API の実行、永続化、実行ログ検索、全体のライフサイクル Hook を提供するスケジューラーモジュールです。
|
|
10
8
|
|
|
11
|
-
##
|
|
12
|
-
|
|
13
|
-
- cron による定期実行とアプリケーションからの手動実行。
|
|
14
|
-
- HTTP、信頼できる JavaScript、アプリ Hook に対応し、再試行とキャンセルを提供。
|
|
15
|
-
- 共有 DB による定義・実行状態・更新可能リースの永続化と結果不明の隔離。
|
|
16
|
-
|
|
17
|
-
## 使い始める
|
|
9
|
+
## クイックスタート
|
|
18
10
|
|
|
19
11
|
### 依存関係
|
|
20
12
|
|
|
21
13
|
- `@h-ai/reldb`:先に共有 DB を初期化し、タスク・journal・リースを保存します。`enableDb` は true のみです。
|
|
22
14
|
|
|
23
|
-
### クイックスタート
|
|
24
|
-
|
|
25
15
|
```ts
|
|
26
16
|
import { reldb } from '@h-ai/reldb'
|
|
27
17
|
import { scheduler } from '@h-ai/scheduler'
|
|
@@ -79,6 +69,59 @@ scheduler.stop()
|
|
|
79
69
|
await scheduler.close()
|
|
80
70
|
```
|
|
81
71
|
|
|
72
|
+
## 機能
|
|
73
|
+
|
|
74
|
+
- cron による定期実行とアプリケーションからの手動実行。
|
|
75
|
+
- HTTP、信頼できる JavaScript、アプリ Hook に対応し、再試行とキャンセルを提供。
|
|
76
|
+
- 共有 DB による定義・実行状態・更新可能リースの永続化と結果不明の隔離。
|
|
77
|
+
|
|
78
|
+
### 操作と入出力
|
|
79
|
+
|
|
80
|
+
本節の完全な初期化手順を先に実行します。例の業務値はホストが検証・認可し、非同期領域結果は success を確認してから data を読みます。void はデータなし完了、null は不存在、同期ファクトリー/ツールは表の型を直接返します。
|
|
81
|
+
|
|
82
|
+
#### scheduler
|
|
83
|
+
|
|
84
|
+
定義管理はタスク・ID・ID+差分・引数なし再読込から void HaiResult。tasks は最終成功の読取専用像で、認可や DB の現在値ではない。
|
|
85
|
+
|
|
86
|
+
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
87
|
+
| ------------------------ | --------------- | -------- | ---------------------------------------------------------------------------------------------- |
|
|
88
|
+
| `scheduler.register` | task | `void` | `await scheduler.register({ id: 'daily', name: 'Daily', cron: '0 2 * * *', timezone: 'UTC' })` |
|
|
89
|
+
| `scheduler.unregister` | taskId | `void` | `await scheduler.unregister('daily')` |
|
|
90
|
+
| `scheduler.updateTask` | taskId, updates | `void` | `await scheduler.updateTask('daily', { enabled: false })` |
|
|
91
|
+
| `scheduler.refreshTasks` | 引数なし | `void` | `await scheduler.refreshTasks()` |
|
|
92
|
+
|
|
93
|
+
#### scheduler
|
|
94
|
+
|
|
95
|
+
start/stop は同期 HaiResult、trigger は ID/パラメーターから試行ログ、getLogs は条件/ページから一覧。stop は進行中副作用を取り消さない。
|
|
96
|
+
|
|
97
|
+
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
98
|
+
| ------------------- | --------------- | ----------------------------------- | ---------------------------------------------------- |
|
|
99
|
+
| `scheduler.start` | 引数なし | `void` | `scheduler.start()` |
|
|
100
|
+
| `scheduler.stop` | 引数なし | `void` | `scheduler.stop()` |
|
|
101
|
+
| `scheduler.trigger` | taskId, options | `TaskExecutionLog` | `await scheduler.trigger('daily')` |
|
|
102
|
+
| `scheduler.getLogs` | options | `PaginatedResult<TaskExecutionLog>` | `await scheduler.getLogs({ page: 1, pageSize: 20 })` |
|
|
103
|
+
|
|
104
|
+
#### scheduler
|
|
105
|
+
|
|
106
|
+
業務/イベント callback の設定・引数なし解除は同期 HaiResult。Hook は signal と外部効果の冪等性を守る。
|
|
107
|
+
|
|
108
|
+
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
109
|
+
| ---------------------- | -------- | -------- | ------------------------------- |
|
|
110
|
+
| `scheduler.setHooks` | hooks | `void` | `scheduler.setHooks(taskHooks)` |
|
|
111
|
+
| `scheduler.clearHooks` | 引数なし | `void` | `scheduler.clearHooks()` |
|
|
112
|
+
|
|
113
|
+
#### scheduler.execution
|
|
114
|
+
|
|
115
|
+
実行台帳。get は occurrenceId から項目/null、list は limit/offset から配列、repairLog は ID でログを冪等補修、resolveUnknown は ID・裁定・expectedUpdatedAt で条件付き解放し void。
|
|
116
|
+
|
|
117
|
+
| 入口 | 入力引数 | 成功結果 | 呼出し例 |
|
|
118
|
+
| ------------------------------------- | ------------------------ | --------------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
119
|
+
| `scheduler.execution.get` | occurrenceId | `SchedulerExecutionEntry \| null` | `await scheduler.execution.get(occurrenceId)` |
|
|
120
|
+
| `scheduler.execution.listUnknown` | options | `SchedulerExecutionEntry[]` | `await scheduler.execution.listUnknown({ limit: 20, offset: 0 })` |
|
|
121
|
+
| `scheduler.execution.listLogFailures` | options | `SchedulerExecutionEntry[]` | `await scheduler.execution.listLogFailures({ limit: 20, offset: 0 })` |
|
|
122
|
+
| `scheduler.execution.repairLog` | occurrenceId | `void` | `await scheduler.execution.repairLog(occurrenceId)` |
|
|
123
|
+
| `scheduler.execution.resolveUnknown` | occurrenceId, resolution | `void` | `await scheduler.execution.resolveUnknown(occurrenceId, { status: 'success', expectedUpdatedAt })` |
|
|
124
|
+
|
|
82
125
|
### 共通タスクモデル
|
|
83
126
|
|
|
84
127
|
```ts
|
|
@@ -184,36 +227,14 @@ const logs = await scheduler.getLogs({
|
|
|
184
227
|
- `tasks` / `hooks` / `config` / `isInitialized` / `isRunning`
|
|
185
228
|
- `close()`
|
|
186
229
|
|
|
187
|
-
### エラー処理
|
|
188
|
-
|
|
189
|
-
`close()` を除くすべての公開 API は `HaiResult<T>` を返します。
|
|
190
|
-
|
|
191
|
-
主なエラーコード:
|
|
192
|
-
|
|
193
|
-
| エラーコード | code | 説明 |
|
|
194
|
-
| ----------------------------------------- | ------------------- | -------------------- |
|
|
195
|
-
| `HaiSchedulerError.NOT_INITIALIZED` | `hai:scheduler:010` | 未初期化 |
|
|
196
|
-
| `HaiSchedulerError.INIT_FAILED` | `hai:scheduler:011` | 初期化に失敗 |
|
|
197
|
-
| `HaiSchedulerError.CONFIG_ERROR` | `hai:scheduler:012` | 設定エラー |
|
|
198
|
-
| `HaiSchedulerError.TASK_NOT_FOUND` | `hai:scheduler:020` | タスクが存在しない |
|
|
199
|
-
| `HaiSchedulerError.TASK_ALREADY_EXISTS` | `hai:scheduler:021` | タスクが既に存在する |
|
|
200
|
-
| `HaiSchedulerError.INVALID_CRON` | `hai:scheduler:022` | 無効な Cron 式 |
|
|
201
|
-
| `HaiSchedulerError.EXECUTION_FAILED` | `hai:scheduler:023` | 実行に失敗 |
|
|
202
|
-
| `HaiSchedulerError.JS_EXECUTION_FAILED` | `hai:scheduler:024` | JS 実行に失敗 |
|
|
203
|
-
| `HaiSchedulerError.API_EXECUTION_FAILED` | `hai:scheduler:025` | API 実行に失敗 |
|
|
204
|
-
| `HaiSchedulerError.DB_SAVE_FAILED` | `hai:scheduler:026` | DB 保存に失敗 |
|
|
205
|
-
| `HaiSchedulerError.ALREADY_RUNNING` | `hai:scheduler:027` | 実行中 |
|
|
206
|
-
| `HaiSchedulerError.NOT_RUNNING` | `hai:scheduler:028` | 実行していない |
|
|
207
|
-
| `HaiSchedulerError.JS_COMPILE_FAILED` | `hai:scheduler:030` | JS コンパイルに失敗 |
|
|
208
|
-
| `HaiSchedulerError.HOOK_EXECUTION_FAILED` | `hai:scheduler:031` | Hook 実行に失敗 |
|
|
209
|
-
| `HaiSchedulerError.LOG_PERSIST_FAILED` | `hai:scheduler:032` | ログ保存未確認 |
|
|
210
|
-
|
|
211
230
|
### 実行時の動作と制約
|
|
212
231
|
|
|
213
232
|
各ノードは同じ共有 RelDB を先に初期化します。ホスト間の本番運用は PostgreSQL/MySQL、SQLite は同じファイルを正しく共有するローカルプロセス向けです。定義、実行 journal、タスク占有、リースを永続化し、`enableDb` は true のみです。キャッシュは不要です。`leaseMs` は既定 300000、範囲 1000~86400000 ミリ秒で実行中に更新します。cron、手動、次周期は同じタスク枠を使い、期限切れ owner は復活・コミットできません。`tasks` は最後に成功した定義スナップショットで、読取失敗や削除・無効化・変更は旧試行を中断します。外部副作用は自動で戻りません。
|
|
214
233
|
|
|
215
234
|
`context.occurrenceId` は永続化された発生 ID で、同じ cron 分と再試行で共通です。手動では 1~128 文字の `idempotencyKey` で元の記録を再利用し、省略時は別発生になります。`executionToken` は取得ごとに変わり、`sequence` / `attempt` が世代を示します。API は `Idempotency-Key`、`X-Scheduler-Sequence`、`X-Scheduler-Attempt`、`X-Scheduler-Task`(ID を percent-encoding)を上書きします。取得済みのライフサイクルイベントも `event.context` を提供し、副作用には同じキーによる排除が必要です。
|
|
216
235
|
|
|
236
|
+
PostgreSQL では、同じ分内の再起動や複数ノードでの同時取得により、既存の実行記録や使用中のタスク枠に行き当たることがあります。スケジューラーはこれらを通常の競合として処理します。`scheduler.execution.get(occurrenceId)` で実行状態を確認し、重複実行を防ぐために実行台帳と一意制約を保持してください。
|
|
237
|
+
|
|
217
238
|
`idempotent` の既定は false。受信側が排除台帳と全副作用をアトミックに永続化する場合だけ true にします。期限切れ実行は true のとき同 occurrenceId で引継ぎ、非冪等実行、または保存済み retry.maxAttempts(既定 1、範囲 1–100、初回と復旧を含む)の予算を使い切った場合は `unknown` となりタスク枠を保持します。停止中の旧プロセスが送った外部操作をリースで撤回できず、ヘッダーだけでは排除できません。再試行もこの宣言に従います。
|
|
218
239
|
|
|
219
240
|
正規状態は `scheduler.execution.get(occurrenceId)`、不明一覧は `listUnknown({ limit, offset })`(limit 1~100、offset 0~1000000)で確認します。信頼された担当者が外部効果を照合し旧 runner の終了を確認してから、`resolveUnknown(id, { status: 'success' | 'discarded', expectedUpdatedAt })` の CAS で枠を解放します。不明実行を直接再投入しないでください。`log.occurrenceId` が照会用受領記録で、`getLogs` は試行の観測ログです。ログ保持は journal と排除履歴を削除しません。
|
|
@@ -224,7 +245,7 @@ const logs = await scheduler.getLogs({
|
|
|
224
245
|
|
|
225
246
|
信頼されたサーバーは `execution.listLogFailures({ limit, offset })`(listUnknown と同じ上限)で pending を監視し、`execution.repairLog(occurrenceId)` で共有 journal から補完します。別ノード・再起動後・同時呼び出しも可能で、固定主キーと全内容の照合によりコミット後の応答消失を排除します。`LOG_PERSIST_FAILED`(032)は pending を維持して安全な警告を出します。終態の保存前に DB 全体が停止した場合は unknown の外部効果を照合し、復元可能な結果があると仮定しないでください。補完と保持処理は業務 Hook を呼ばず、保持失敗は警告のみです。`onTaskFinish` は未確定のローカル業務終了通知で、保存確認は trigger の戻り値と execution.get.logPersistence を使います。
|
|
226
247
|
|
|
227
|
-
取得前の競合・スキップの interrupted は観測ログで、補完できる確定終態はありません。応答が確認できなければ unconfirmed です。JSON 列で MySQL の 255
|
|
248
|
+
取得前の競合・スキップの interrupted は観測ログで、補完できる確定終態はありません。応答が確認できなければ unconfirmed です。JSON 列で MySQL の 255 文字制限を避け、完全な結果と全再試行を保持します。実行台帳は観測ログから独立します。終了は補完処理を待つため、DB より先に scheduler を終了してください。
|
|
228
249
|
|
|
229
250
|
```ts
|
|
230
251
|
const result = await scheduler.trigger('cleanup', { idempotencyKey: 'cleanup-2026-10-23' })
|
|
@@ -254,11 +275,45 @@ cron は分単位で照合し、同じ分から永続 occurrenceId を生成し
|
|
|
254
275
|
|
|
255
276
|
Reach 通知を実行するタスクでは、調度ロックやタスク完了だけで外部配信の一意性は保証できません。[Reach キューの意味](../reach/README.ja.md) に従い、永続化された queueId を使ってください。HTTP 受信側は副作用と重複排除を原子的に保存し、SMTP/SMS の配信中の結果不明は手動照合します。スケジューラーの再試行で無条件に再送しないでください。
|
|
256
277
|
|
|
257
|
-
|
|
278
|
+
### 定義の整合性と永続化の準備
|
|
258
279
|
|
|
259
280
|
定義の更新読込、登録、変更、削除は、変更に必要な読込と保存を含めプロセス内で受付順に調整します。正当な並行登録はスナップショットの交錯だけでは失敗せず、実際の DB 障害は失敗として返します。close は入口と runner を停止し、読取待機と未着手の書込を中止して、開始済みの永続書込を待ってから状態を解放します。遅延スナップショットは反映しません。業務コールバックはこのキューを占有しません。ノード間の整合性は引き続き共有 DB、バージョンとリースで保証し、この調整を分散ロックの代替にしません。
|
|
260
281
|
|
|
261
|
-
RelDB
|
|
282
|
+
RelDB 初期化後の `migrateScheduler({ dryRun: true })` で永続構造を事前確認し、scheduler.init はリポジトリ作成前に対応する準備を実行します。バックアップと排他変更時間を確保し、失敗時は起動を止め、実行台帳と観測ログを区別してください。
|
|
283
|
+
|
|
284
|
+
## 設定
|
|
285
|
+
|
|
286
|
+
ライフサイクル。init にバックエンド/業務設定を渡し成功後に使用します。借用依存先の解放前に close の完了を待ち、正確な戻り値は例と公開署名に従います。
|
|
287
|
+
|
|
288
|
+
設定はホストが読込・検証してから渡します。秘密はサーバーの非公開環境に保存し、利用場面に応じてバックエンド・容量・期限・ログを選びます。変更後は再初期化の結果を確認してください。
|
|
289
|
+
|
|
290
|
+
[項目別の用途・適用場面・例](../../docs/usage/configuration/operations.md).
|
|
291
|
+
|
|
292
|
+
## エラー処理
|
|
293
|
+
|
|
294
|
+
領域操作は result.success を確認し、失敗時はモジュールのエラー定義と安全な説明を使います。コード・関連 ID・秘匿した原因をサーバーログに残します。同期ツール・ファクトリー・ストリーム反復・ライフサイクルは各署名に従い、Promise 完了だけで成功と判断しません。回復条件は各機能を参照してください。
|
|
295
|
+
|
|
296
|
+
`close()` を除くすべての公開 API は `HaiResult<T>` を返します。
|
|
297
|
+
|
|
298
|
+
主なエラーコード:
|
|
299
|
+
|
|
300
|
+
| エラーコード | code | 説明 |
|
|
301
|
+
| ----------------------------------------- | ------------------- | -------------------- |
|
|
302
|
+
| `HaiSchedulerError.NOT_INITIALIZED` | `hai:scheduler:010` | 未初期化 |
|
|
303
|
+
| `HaiSchedulerError.INIT_FAILED` | `hai:scheduler:011` | 初期化に失敗 |
|
|
304
|
+
| `HaiSchedulerError.CONFIG_ERROR` | `hai:scheduler:012` | 設定エラー |
|
|
305
|
+
| `HaiSchedulerError.TASK_NOT_FOUND` | `hai:scheduler:020` | タスクが存在しない |
|
|
306
|
+
| `HaiSchedulerError.TASK_ALREADY_EXISTS` | `hai:scheduler:021` | タスクが既に存在する |
|
|
307
|
+
| `HaiSchedulerError.INVALID_CRON` | `hai:scheduler:022` | 無効な Cron 式 |
|
|
308
|
+
| `HaiSchedulerError.EXECUTION_FAILED` | `hai:scheduler:023` | 実行に失敗 |
|
|
309
|
+
| `HaiSchedulerError.JS_EXECUTION_FAILED` | `hai:scheduler:024` | JS 実行に失敗 |
|
|
310
|
+
| `HaiSchedulerError.API_EXECUTION_FAILED` | `hai:scheduler:025` | API 実行に失敗 |
|
|
311
|
+
| `HaiSchedulerError.DB_SAVE_FAILED` | `hai:scheduler:026` | DB 保存に失敗 |
|
|
312
|
+
| `HaiSchedulerError.ALREADY_RUNNING` | `hai:scheduler:027` | 実行中 |
|
|
313
|
+
| `HaiSchedulerError.NOT_RUNNING` | `hai:scheduler:028` | 実行していない |
|
|
314
|
+
| `HaiSchedulerError.JS_COMPILE_FAILED` | `hai:scheduler:030` | JS コンパイルに失敗 |
|
|
315
|
+
| `HaiSchedulerError.HOOK_EXECUTION_FAILED` | `hai:scheduler:031` | Hook 実行に失敗 |
|
|
316
|
+
| `HaiSchedulerError.LOG_PERSIST_FAILED` | `hai:scheduler:032` | ログ保存未確認 |
|
|
262
317
|
|
|
263
318
|
## 開発とテスト
|
|
264
319
|
|
package/README.md
CHANGED
|
@@ -4,24 +4,14 @@
|
|
|
4
4
|
|
|
5
5
|
[框架首页](../../README.md) · 相关模块:[@h-ai/core](../core/README.md) · [@h-ai/reldb](../reldb/README.md)
|
|
6
6
|
|
|
7
|
-
## 简介
|
|
8
|
-
|
|
9
7
|
定时任务调度模块,支持统一任务模型、cron 调度、JS 函数字符串 / HTTP API 执行、任务持久化、执行日志查询,以及全局任务生命周期回调。
|
|
10
8
|
|
|
11
|
-
##
|
|
12
|
-
|
|
13
|
-
- 按 cron 定时执行,也可从业务代码手动触发。
|
|
14
|
-
- 支持 HTTP、受信任的 JavaScript 和应用 Hook,提供重试与取消。
|
|
15
|
-
- 共享数据库持久化任务、执行状态与可续期租约,支持未知结果隔离。
|
|
16
|
-
|
|
17
|
-
## 使用入门
|
|
9
|
+
## 快速开始
|
|
18
10
|
|
|
19
11
|
### 依赖
|
|
20
12
|
|
|
21
13
|
- `@h-ai/reldb` — 必须先初始化共享数据库,保存任务、执行 journal 与自动续租;`enableDb` 只能为 true。
|
|
22
14
|
|
|
23
|
-
### 快速开始
|
|
24
|
-
|
|
25
15
|
```ts
|
|
26
16
|
import { reldb } from '@h-ai/reldb'
|
|
27
17
|
import { scheduler } from '@h-ai/scheduler'
|
|
@@ -79,6 +69,59 @@ scheduler.stop()
|
|
|
79
69
|
await scheduler.close()
|
|
80
70
|
```
|
|
81
71
|
|
|
72
|
+
## 功能
|
|
73
|
+
|
|
74
|
+
- 按 cron 定时执行,也可从业务代码手动触发。
|
|
75
|
+
- 支持 HTTP、受信任的 JavaScript 和应用 Hook,提供重试与取消。
|
|
76
|
+
- 共享数据库持久化任务、执行状态与可续期租约,支持未知结果隔离。
|
|
77
|
+
|
|
78
|
+
### 功能输入输出
|
|
79
|
+
|
|
80
|
+
以下片段依赖本节完整初始化流程。示例中的业务值由宿主校验和授权后传入;异步领域结果先判断 success,再读取 data。表中 void 表示操作已完成且没有返回数据,null 表示不存在;同步工厂/工具直接返回表中类型。
|
|
81
|
+
|
|
82
|
+
#### scheduler
|
|
83
|
+
|
|
84
|
+
任务定义管理:完整任务、ID、ID+补丁或无参数刷新,分别返回 void HaiResult。tasks 是最近成功只读快照,不是权限或实时数据库依据。
|
|
85
|
+
|
|
86
|
+
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
87
|
+
| ------------------------ | --------------- | -------- | ---------------------------------------------------------------------------------------------- |
|
|
88
|
+
| `scheduler.register` | task | `void` | `await scheduler.register({ id: 'daily', name: 'Daily', cron: '0 2 * * *', timezone: 'UTC' })` |
|
|
89
|
+
| `scheduler.unregister` | taskId | `void` | `await scheduler.unregister('daily')` |
|
|
90
|
+
| `scheduler.updateTask` | taskId, updates | `void` | `await scheduler.updateTask('daily', { enabled: false })` |
|
|
91
|
+
| `scheduler.refreshTasks` | 无参数 | `void` | `await scheduler.refreshTasks()` |
|
|
92
|
+
|
|
93
|
+
#### scheduler
|
|
94
|
+
|
|
95
|
+
start/stop 无参数返回同步 HaiResult;trigger 输入任务 ID/参数返回一次执行日志;getLogs 输入过滤/分页返回日志页。stop 不代表在途副作用已撤销。
|
|
96
|
+
|
|
97
|
+
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
98
|
+
| ------------------- | --------------- | ----------------------------------- | ---------------------------------------------------- |
|
|
99
|
+
| `scheduler.start` | 无参数 | `void` | `scheduler.start()` |
|
|
100
|
+
| `scheduler.stop` | 无参数 | `void` | `scheduler.stop()` |
|
|
101
|
+
| `scheduler.trigger` | taskId, options | `TaskExecutionLog` | `await scheduler.trigger('daily')` |
|
|
102
|
+
| `scheduler.getLogs` | options | `PaginatedResult<TaskExecutionLog>` | `await scheduler.getLogs({ page: 1, pageSize: 20 })` |
|
|
103
|
+
|
|
104
|
+
#### scheduler
|
|
105
|
+
|
|
106
|
+
接入业务执行/事件,输入回调集合或无参清除,返回同步 HaiResult。Hook 必须响应 signal 并保证外部效果幂等。
|
|
107
|
+
|
|
108
|
+
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
109
|
+
| ---------------------- | -------- | -------- | ------------------------------- |
|
|
110
|
+
| `scheduler.setHooks` | hooks | `void` | `scheduler.setHooks(taskHooks)` |
|
|
111
|
+
| `scheduler.clearHooks` | 无参数 | `void` | `scheduler.clearHooks()` |
|
|
112
|
+
|
|
113
|
+
#### scheduler.execution
|
|
114
|
+
|
|
115
|
+
权威执行账本。get 输入 occurrenceId 返回项/null;两种 list 输入 limit/offset 返回数组;repairLog 输入 ID 幂等补日志;resolveUnknown 输入 ID、人工终态及 expectedUpdatedAt 条件释放槽位,返回 void。
|
|
116
|
+
|
|
117
|
+
| 入口 | 输入参数 | 成功结果 | 调用示例 |
|
|
118
|
+
| ------------------------------------- | ------------------------ | --------------------------------- | -------------------------------------------------------------------------------------------------- |
|
|
119
|
+
| `scheduler.execution.get` | occurrenceId | `SchedulerExecutionEntry \| null` | `await scheduler.execution.get(occurrenceId)` |
|
|
120
|
+
| `scheduler.execution.listUnknown` | options | `SchedulerExecutionEntry[]` | `await scheduler.execution.listUnknown({ limit: 20, offset: 0 })` |
|
|
121
|
+
| `scheduler.execution.listLogFailures` | options | `SchedulerExecutionEntry[]` | `await scheduler.execution.listLogFailures({ limit: 20, offset: 0 })` |
|
|
122
|
+
| `scheduler.execution.repairLog` | occurrenceId | `void` | `await scheduler.execution.repairLog(occurrenceId)` |
|
|
123
|
+
| `scheduler.execution.resolveUnknown` | occurrenceId, resolution | `void` | `await scheduler.execution.resolveUnknown(occurrenceId, { status: 'success', expectedUpdatedAt })` |
|
|
124
|
+
|
|
82
125
|
### 统一任务模型
|
|
83
126
|
|
|
84
127
|
```ts
|
|
@@ -184,36 +227,14 @@ const logs = await scheduler.getLogs({
|
|
|
184
227
|
- `tasks` / `hooks` / `config` / `isInitialized` / `isRunning`
|
|
185
228
|
- `close()`
|
|
186
229
|
|
|
187
|
-
### 错误处理
|
|
188
|
-
|
|
189
|
-
所有公共 API(除 `close()`)返回 `HaiResult<T>`。
|
|
190
|
-
|
|
191
|
-
常用错误码:
|
|
192
|
-
|
|
193
|
-
| 错误码 | code | 说明 |
|
|
194
|
-
| ----------------------------------------- | ------------------- | ---------------- |
|
|
195
|
-
| `HaiSchedulerError.NOT_INITIALIZED` | `hai:scheduler:010` | 未初始化 |
|
|
196
|
-
| `HaiSchedulerError.INIT_FAILED` | `hai:scheduler:011` | 初始化失败 |
|
|
197
|
-
| `HaiSchedulerError.CONFIG_ERROR` | `hai:scheduler:012` | 配置错误 |
|
|
198
|
-
| `HaiSchedulerError.TASK_NOT_FOUND` | `hai:scheduler:020` | 任务不存在 |
|
|
199
|
-
| `HaiSchedulerError.TASK_ALREADY_EXISTS` | `hai:scheduler:021` | 任务已存在 |
|
|
200
|
-
| `HaiSchedulerError.INVALID_CRON` | `hai:scheduler:022` | Cron 表达式无效 |
|
|
201
|
-
| `HaiSchedulerError.EXECUTION_FAILED` | `hai:scheduler:023` | 执行失败 |
|
|
202
|
-
| `HaiSchedulerError.JS_EXECUTION_FAILED` | `hai:scheduler:024` | JS 执行失败 |
|
|
203
|
-
| `HaiSchedulerError.API_EXECUTION_FAILED` | `hai:scheduler:025` | API 执行失败 |
|
|
204
|
-
| `HaiSchedulerError.DB_SAVE_FAILED` | `hai:scheduler:026` | DB 保存失败 |
|
|
205
|
-
| `HaiSchedulerError.ALREADY_RUNNING` | `hai:scheduler:027` | 已在运行 |
|
|
206
|
-
| `HaiSchedulerError.NOT_RUNNING` | `hai:scheduler:028` | 未在运行 |
|
|
207
|
-
| `HaiSchedulerError.JS_COMPILE_FAILED` | `hai:scheduler:030` | JS 编译失败 |
|
|
208
|
-
| `HaiSchedulerError.HOOK_EXECUTION_FAILED` | `hai:scheduler:031` | Hook 执行失败 |
|
|
209
|
-
| `HaiSchedulerError.LOG_PERSIST_FAILED` | `hai:scheduler:032` | 日志持久化未确认 |
|
|
210
|
-
|
|
211
230
|
### 运行行为与边界
|
|
212
231
|
|
|
213
232
|
所有节点必须先初始化同一共享 RelDB(跨主机生产使用 PostgreSQL/MySQL;SQLite 文件只适合可正确共享同一文件的本机进程)。数据库保存任务、执行 journal、全局任务占位和租约,`enableDb` 只能为 true;不再依赖缓存。`leaseMs` 默认 300000,范围 1000~86400000 毫秒,执行中自动续期。cron、手动和跨周期执行均争用同一任务槽,过期 owner 不能续活或提交。节点每个 `tickInterval` 刷新定义,`tasks` 只是最近成功快照;定义读取失败、删除、禁用、改期均中断旧尝试,已发生副作用不会回滚。
|
|
214
233
|
|
|
215
234
|
`context.occurrenceId` 是持久发生标识;同一 cron 分钟跨节点一致,手动可传 1~128 字符 `idempotencyKey` 重用原记录,省略时每次独立。`executionToken` 每次领取变化,`sequence` / `attempt` 提供执行代信息。API 会覆盖 `Idempotency-Key`、`X-Scheduler-Sequence`、`X-Scheduler-Attempt`、`X-Scheduler-Task`(任务 ID 使用 percent-encoding)。Hook 及生命周期回调已领取时的 `event.context` 使用同一发生标识;观测回调若产生副作用也须去重。
|
|
216
235
|
|
|
236
|
+
使用 PostgreSQL 时,同一分钟重启或多个节点同时领取可能遇到已有执行记录或被占用的任务槽。调度器将这些冲突作为正常竞争处理。排查任务是否完成时,用 `scheduler.execution.get(occurrenceId)` 查看执行状态,并保留账本和唯一约束以防止重复执行。
|
|
237
|
+
|
|
217
238
|
`idempotent` 默认为 false;只有接收端已将幂等账本和全部副作用原子持久提交,才声明 true。租约过期的已执行任务仅在 true 时以同 occurrenceId 接管;非幂等或耗尽本 occurrence 保存的 retry.maxAttempts(默认 1,范围 1–100,包含首次执行及恢复)时进入 `unknown` 并继续占住任务槽。租约无法强制撤销暂停进程已发出的外部操作,单有 HTTP 头不构成去重实现。重试同样受幂等声明约束。
|
|
218
239
|
|
|
219
240
|
`scheduler.execution.get(occurrenceId)` 查询权威状态;`listUnknown({ limit, offset })` 分页获取未知结果,limit 为 1~100,offset 为 0~1000000。可信人工先核实外部效果、确认旧 runner 已终止,再按 `expectedUpdatedAt` CAS 调用 `resolveUnknown(id, { status: 'success' | 'discarded', expectedUpdatedAt })` 释放占位;不能直接把 unknown 重排。`log.occurrenceId` 可作查询回执;`getLogs` 仅为尝试观测日志,日志保留策略不删除 journal/幂等历史。
|
|
@@ -224,7 +245,7 @@ const logs = await scheduler.getLogs({
|
|
|
224
245
|
|
|
225
246
|
可信服务端用 `execution.listLogFailures({ limit, offset })` 监控 pending(范围与 listUnknown 相同),用 `execution.repairLog(occurrenceId)` 从共享 journal 幂等补写;可跨节点、重启及并发调用。写入已提交但回执丢失时通过固定主键和完整内容核对去重。补写返回 `LOG_PERSIST_FAILED`(032)时继续保留 pending,并输出安全告警;全部数据库不可用且终态未提交时仍按 unknown 核对外部效果,不能假定存在可恢复结果。补写与日志保留均不调用业务 Hook。保留策略失败仅告警,不撤销已保存日志。`onTaskFinish` 是本地业务完成通知,其 unconfirmed 状态不是持久化确认;以 trigger 返回值及 execution.get 的 logPersistence 为准。
|
|
226
247
|
|
|
227
|
-
领取前竞争/跳过的 interrupted 仅为观测日志,没有可补写的终态;其写入未确认时返回 unconfirmed。JSON 大载荷保存完整结果和全部重试记录,避免 MySQL 的 255
|
|
248
|
+
领取前竞争/跳过的 interrupted 仅为观测日志,没有可补写的终态;其写入未确认时返回 unconfirmed。JSON 大载荷保存完整结果和全部重试记录,避免 MySQL 的 255 字符截断;执行账本保持独立。关闭会等待在途补写,先关闭 scheduler 再关闭数据库。
|
|
228
249
|
|
|
229
250
|
```ts
|
|
230
251
|
const result = await scheduler.trigger('cleanup', { idempotencyKey: 'cleanup-2026-10-23' })
|
|
@@ -254,11 +275,45 @@ API 任务的 `timeout`(默认 30000 毫秒)覆盖请求和完整响应体
|
|
|
254
275
|
|
|
255
276
|
调度任务触发 Reach 通知时,调度锁或任务完成不等于外部消息只投递一次。按 [Reach 队列语义](../reach/README.md) 使用持久 queueId;HTTP 接收端须原子持久去重,SMTP/短信等在途未知结果须人工核对,不能由调度重试直接重发。
|
|
256
277
|
|
|
257
|
-
|
|
278
|
+
### 定义一致性与持久化准备
|
|
258
279
|
|
|
259
280
|
任务定义的刷新、注册、更新和删除在同一进程内按接收顺序协调,包含写操作所需的刷新与提交。合法并发注册不会仅因快照交错而失败;真实数据库故障仍返回失败。close 先停止入口和 runner,取消只读等待和尚未开始写入的操作,再等待已开始的持久写入;迟到快照不发布,避免关闭后旧操作重新填充任务表。执行回调不占用这条队列;跨节点仍依靠共享数据库、版本与租约,不把进程内协调当分布式锁。
|
|
260
281
|
|
|
261
|
-
RelDB
|
|
282
|
+
RelDB 初始化后可调用 `migrateScheduler({ dryRun: true })` 预检持久化结构;scheduler.init 在创建仓储前执行支持的结构准备。应用负责备份与独占变更窗口,结构准备失败时停止启动,不把执行账本与观测日志混为一体。
|
|
283
|
+
|
|
284
|
+
## 配置
|
|
285
|
+
|
|
286
|
+
生命周期:init 输入后端/业务配置,成功后才能使用;close 在释放借用依赖前等待完成。返回值以快速开始示例和公开签名为准。
|
|
287
|
+
|
|
288
|
+
配置由宿主加载和校验,再传入本模块;私密值放服务端私有环境,不传到浏览器。按实际使用场景逐项选择后端、容量、期限和日志策略,修改后重新初始化并核验成功结果。
|
|
289
|
+
|
|
290
|
+
[逐项配置说明、适用场景和示例](../../docs/usage/configuration/operations.md).
|
|
291
|
+
|
|
292
|
+
## 错误处理
|
|
293
|
+
|
|
294
|
+
领域操作先判断 `result.success`,失败按本模块错误定义与安全提示处理,服务端保留错误码、关联编号和脱敏原因。同步工具、工厂、流迭代及生命周期按各自签名处理,不把 Promise 完成视为业务成功。具体失败与恢复边界见对应功能。
|
|
295
|
+
|
|
296
|
+
所有公共 API(除 `close()`)返回 `HaiResult<T>`。
|
|
297
|
+
|
|
298
|
+
常用错误码:
|
|
299
|
+
|
|
300
|
+
| 错误码 | code | 说明 |
|
|
301
|
+
| ----------------------------------------- | ------------------- | ---------------- |
|
|
302
|
+
| `HaiSchedulerError.NOT_INITIALIZED` | `hai:scheduler:010` | 未初始化 |
|
|
303
|
+
| `HaiSchedulerError.INIT_FAILED` | `hai:scheduler:011` | 初始化失败 |
|
|
304
|
+
| `HaiSchedulerError.CONFIG_ERROR` | `hai:scheduler:012` | 配置错误 |
|
|
305
|
+
| `HaiSchedulerError.TASK_NOT_FOUND` | `hai:scheduler:020` | 任务不存在 |
|
|
306
|
+
| `HaiSchedulerError.TASK_ALREADY_EXISTS` | `hai:scheduler:021` | 任务已存在 |
|
|
307
|
+
| `HaiSchedulerError.INVALID_CRON` | `hai:scheduler:022` | Cron 表达式无效 |
|
|
308
|
+
| `HaiSchedulerError.EXECUTION_FAILED` | `hai:scheduler:023` | 执行失败 |
|
|
309
|
+
| `HaiSchedulerError.JS_EXECUTION_FAILED` | `hai:scheduler:024` | JS 执行失败 |
|
|
310
|
+
| `HaiSchedulerError.API_EXECUTION_FAILED` | `hai:scheduler:025` | API 执行失败 |
|
|
311
|
+
| `HaiSchedulerError.DB_SAVE_FAILED` | `hai:scheduler:026` | DB 保存失败 |
|
|
312
|
+
| `HaiSchedulerError.ALREADY_RUNNING` | `hai:scheduler:027` | 已在运行 |
|
|
313
|
+
| `HaiSchedulerError.NOT_RUNNING` | `hai:scheduler:028` | 未在运行 |
|
|
314
|
+
| `HaiSchedulerError.JS_COMPILE_FAILED` | `hai:scheduler:030` | JS 编译失败 |
|
|
315
|
+
| `HaiSchedulerError.HOOK_EXECUTION_FAILED` | `hai:scheduler:031` | Hook 执行失败 |
|
|
316
|
+
| `HaiSchedulerError.LOG_PERSIST_FAILED` | `hai:scheduler:032` | 日志持久化未确认 |
|
|
262
317
|
|
|
263
318
|
## 开发测试
|
|
264
319
|
|
package/dist/index.d.ts
CHANGED
|
@@ -867,4 +867,5 @@ declare function migrateScheduler(options?: {
|
|
|
867
867
|
dryRun?: boolean;
|
|
868
868
|
}): Promise<_h_ai_core.HaiResult<_h_ai_reldb.SchemaMigrationPlan>>;
|
|
869
869
|
|
|
870
|
-
export {
|
|
870
|
+
export { ExecutionResolutionSchema, HaiSchedulerError, SchedulerConfigSchema, TriggerTaskSchema, migrateScheduler, scheduler };
|
|
871
|
+
export type { ApiTaskConfig, ExecutionStatus, JsTaskConfig, JsTaskHandler, LogQueryOptions, SchedulerConfig, SchedulerConfigInput, SchedulerExecutionEntry, SchedulerExecutionOperations, SchedulerExecutionState, SchedulerFunctions, SchedulerInitInput, SchedulerLogCleanupPolicy, SchedulerTaskContext, SchedulerTaskExecuteEvent, SchedulerTaskFinishEvent, SchedulerTaskHooks, SchedulerTaskInterruptedEvent, SchedulerTaskStartEvent, TaskDefinition, TaskExecutionLog, TaskExecutionTargetType, TaskHandlerConfig, TaskHandlerKind, TaskLogPersistence, TaskParams, TaskRetryPolicy, TaskTriggerInfo, TaskTriggerType, TaskUpdateInput, TriggerTaskInput };
|