@asabot/core 0.1.0 → 0.2.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/CHANGELOG.md +17 -0
- package/README.md +93 -14
- package/asabot.config.example.yaml +47 -29
- package/dist/adapters/feishu/adapter.d.ts +19 -0
- package/dist/adapters/feishu/adapter.js +621 -0
- package/dist/adapters/feishu/api.d.ts +142 -0
- package/dist/adapters/feishu/api.js +306 -0
- package/dist/adapters/feishu/bot.d.ts +95 -0
- package/dist/adapters/feishu/bot.js +539 -0
- package/dist/adapters/feishu/cards.d.ts +93 -0
- package/dist/adapters/feishu/cards.js +106 -0
- package/dist/adapters/feishu/config.d.ts +13 -0
- package/dist/adapters/feishu/config.js +36 -0
- package/dist/adapters/feishu/events.d.ts +33 -0
- package/dist/adapters/feishu/events.js +14 -0
- package/dist/adapters/feishu/index.d.ts +8 -0
- package/dist/adapters/feishu/index.js +5 -0
- package/dist/adapters/feishu/message.d.ts +64 -0
- package/dist/adapters/feishu/message.js +197 -0
- package/dist/adapters/feishu/transport.d.ts +34 -0
- package/dist/adapters/feishu/transport.js +110 -0
- package/dist/adapters/index.d.ts +1 -7
- package/dist/adapters/index.js +75 -6
- package/dist/adapters/loader.d.ts +6 -0
- package/dist/adapters/loader.js +73 -0
- package/dist/adapters/media-source.d.ts +7 -0
- package/dist/adapters/media-source.js +137 -0
- package/dist/adapters/onebot11/adapter.d.ts +5 -0
- package/dist/adapters/onebot11/adapter.js +23 -11
- package/dist/adapters/onebot11/api.d.ts +4 -1
- package/dist/adapters/onebot11/api.js +21 -8
- package/dist/adapters/onebot11/errors.d.ts +3 -0
- package/dist/adapters/onebot11/errors.js +6 -0
- package/dist/adapters/virtual/index.js +7 -1
- package/dist/adapters/wecom/adapter.d.ts +14 -0
- package/dist/adapters/wecom/adapter.js +220 -0
- package/dist/adapters/wecom/bot.d.ts +71 -0
- package/dist/adapters/wecom/bot.js +312 -0
- package/dist/adapters/wecom/cards.d.ts +37 -0
- package/dist/adapters/wecom/cards.js +30 -0
- package/dist/adapters/wecom/config.d.ts +8 -0
- package/dist/adapters/wecom/config.js +10 -0
- package/dist/adapters/wecom/events.d.ts +93 -0
- package/dist/adapters/wecom/events.js +46 -0
- package/dist/adapters/wecom/index.d.ts +7 -0
- package/dist/adapters/wecom/index.js +21 -0
- package/dist/adapters/wecom/media.d.ts +50 -0
- package/dist/adapters/wecom/media.js +149 -0
- package/dist/adapters/wecom/message.d.ts +151 -0
- package/dist/adapters/wecom/message.js +116 -0
- package/dist/adapters/wecom/transport.d.ts +39 -0
- package/dist/adapters/wecom/transport.js +116 -0
- package/dist/adapters/weixin-clawbot/adapter.d.ts +16 -0
- package/dist/adapters/weixin-clawbot/adapter.js +173 -0
- package/dist/adapters/weixin-clawbot/bot.d.ts +41 -0
- package/dist/adapters/weixin-clawbot/bot.js +254 -0
- package/dist/adapters/weixin-clawbot/index.d.ts +2 -0
- package/dist/adapters/weixin-clawbot/index.js +19 -0
- package/dist/adapters/weixin-clawbot/media.d.ts +57 -0
- package/dist/adapters/weixin-clawbot/media.js +196 -0
- package/dist/adapters/weixin-clawbot/message.d.ts +12 -0
- package/dist/adapters/weixin-clawbot/message.js +79 -0
- package/dist/adapters/weixin-clawbot/protocol.d.ts +145 -0
- package/dist/adapters/weixin-clawbot/protocol.js +178 -0
- package/dist/adapters/weixin-clawbot/setup.d.ts +2 -0
- package/dist/adapters/weixin-clawbot/setup.js +121 -0
- package/dist/bootstrap.d.ts +5 -0
- package/dist/bootstrap.js +5 -20
- package/dist/cli.js +9 -3
- package/dist/core/adapter.d.ts +69 -3
- package/dist/core/adapter.js +11 -1
- package/dist/core/app.d.ts +12 -9
- package/dist/core/app.js +50 -51
- package/dist/core/bot-accounts.d.ts +28 -0
- package/dist/core/bot-accounts.js +78 -0
- package/dist/core/bot-policies.d.ts +30 -0
- package/dist/core/bot-policies.js +112 -0
- package/dist/core/bot.d.ts +19 -1
- package/dist/core/bot.js +13 -0
- package/dist/core/capabilities.d.ts +54 -0
- package/dist/core/capabilities.js +25 -0
- package/dist/core/config/schema.d.ts +61 -8
- package/dist/core/config/schema.js +15 -3
- package/dist/core/config/write.js +5 -1
- package/dist/core/connections.d.ts +84 -0
- package/dist/core/connections.js +326 -0
- package/dist/core/delivery.d.ts +53 -0
- package/dist/core/delivery.js +115 -0
- package/dist/core/dispatch/api.d.ts +3 -1
- package/dist/core/dispatch/api.js +12 -5
- package/dist/core/dispatch/dispatcher.d.ts +1 -0
- package/dist/core/dispatch/dispatcher.js +35 -15
- package/dist/core/dispatch/outgoing.d.ts +1 -0
- package/dist/core/dispatch/outgoing.js +5 -3
- package/dist/core/dispatch/trace.d.ts +2 -0
- package/dist/core/dispatch/types.d.ts +6 -0
- package/dist/core/dispatch/types.js +1 -2
- package/dist/core/errors.d.ts +4 -1
- package/dist/core/errors.js +7 -1
- package/dist/core/event/session.d.ts +3 -1
- package/dist/core/event/session.js +7 -4
- package/dist/core/event/types.d.ts +5 -1
- package/dist/core/identity.d.ts +18 -0
- package/dist/core/identity.js +31 -0
- package/dist/core/logger.js +9 -2
- package/dist/core/message/segment.js +3 -13
- package/dist/core/message/types.d.ts +2 -0
- package/dist/core/permission.d.ts +2 -1
- package/dist/core/permission.js +7 -2
- package/dist/core/plugin/context.d.ts +17 -11
- package/dist/core/plugin/context.js +48 -21
- package/dist/core/plugin/definition.d.ts +7 -0
- package/dist/core/plugin/execution.d.ts +3 -0
- package/dist/core/plugin/execution.js +3 -0
- package/dist/core/plugin/icon.d.ts +2 -0
- package/dist/core/plugin/icon.js +14 -0
- package/dist/core/plugin/manager.d.ts +26 -7
- package/dist/core/plugin/manager.js +179 -56
- package/dist/core/plugin/packages.d.ts +4 -0
- package/dist/core/plugin/packages.js +39 -9
- package/dist/core/plugin/tasks.d.ts +131 -24
- package/dist/core/plugin/tasks.js +517 -117
- package/dist/core/plugin/types.d.ts +14 -0
- package/dist/core/ratelimit.js +6 -1
- package/dist/core/storage/index.d.ts +3 -1
- package/dist/core/storage/index.js +52 -2
- package/dist/core/target.d.ts +24 -6
- package/dist/core/target.js +26 -6
- package/dist/core/utils/merge.d.ts +3 -0
- package/dist/core/utils/merge.js +18 -0
- package/dist/core/utils/redact.d.ts +6 -0
- package/dist/core/utils/redact.js +76 -0
- package/dist/index.d.ts +14 -6
- package/dist/index.js +7 -2
- package/dist/plugins/admin.js +30 -3
- package/dist/plugins/help.js +1 -0
- package/dist/plugins/history.d.ts +4 -0
- package/dist/plugins/history.js +13 -3
- package/dist/plugins/http.js +1 -0
- package/dist/plugins/long-message.js +20 -12
- package/dist/plugins/status.js +1 -0
- package/dist/server/auth.d.ts +5 -1
- package/dist/server/auth.js +11 -7
- package/dist/server/connection-setups.d.ts +126 -0
- package/dist/server/connection-setups.js +188 -0
- package/dist/server/groups.d.ts +1 -0
- package/dist/server/groups.js +8 -8
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.js +230 -29
- package/dist/server/schemas.d.ts +6 -2
- package/dist/server/settings.d.ts +66 -20
- package/dist/server/settings.js +158 -61
- package/dist/server/views.d.ts +97 -17
- package/dist/server/views.js +48 -13
- package/dist/testing/create-test-app.js +2 -2
- package/dist/testing/dispatch-fixture.js +2 -1
- package/dist/testing/fake-bot.d.ts +2 -1
- package/dist/testing/fake-bot.js +4 -1
- package/docs/DEPLOY.md +211 -0
- package/docs/FEISHU.md +170 -0
- package/docs/WECOM.md +107 -0
- package/docs/WEIXIN-CLAWBOT.md +56 -0
- package/package.json +29 -3
- package/web/dist/assets/index-ogXTSYEt.css +2 -0
- package/web/dist/assets/index-r9XycpMd.js +51 -0
- package/web/dist/assets/{markdown-CDlgpI7K.js → markdown-CIohfKSa.js} +3 -3
- package/web/dist/index.html +2 -2
- package/web/dist/plugin-pages/_sdk.js +26 -1
- package/web/dist/assets/index-BI5GCpiI.css +0 -2
- package/web/dist/assets/index-C-rshHwD.js +0 -51
|
@@ -1,143 +1,543 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { durationSchema } from '../config/schema.js';
|
|
4
|
+
import { DeliveryError } from '../delivery.js';
|
|
2
5
|
import { scheduleTimeout } from '../dispatch/timer.js';
|
|
3
6
|
import { parseDuration } from '../utils/duration.js';
|
|
4
|
-
|
|
7
|
+
import { redactText } from '../utils/redact.js';
|
|
8
|
+
import { pluginExecution } from './execution.js';
|
|
9
|
+
export const taskStates = [
|
|
10
|
+
'pending',
|
|
11
|
+
'running',
|
|
12
|
+
'retry_wait',
|
|
13
|
+
'cancelling',
|
|
14
|
+
'succeeded',
|
|
15
|
+
'failed',
|
|
16
|
+
'cancelled',
|
|
17
|
+
];
|
|
18
|
+
export class TaskConflictError extends Error {
|
|
19
|
+
}
|
|
20
|
+
const terminal = new Set(['succeeded', 'failed', 'cancelled']);
|
|
21
|
+
const identity = (plugin, name, key) => JSON.stringify([plugin, name, key]);
|
|
22
|
+
const policySchema = z
|
|
23
|
+
.object({
|
|
24
|
+
retry: z
|
|
25
|
+
.object({
|
|
26
|
+
maxRetries: z.number().int().nonnegative(),
|
|
27
|
+
delay: durationSchema.default(5_000),
|
|
28
|
+
maxDelay: durationSchema.default(300_000),
|
|
29
|
+
})
|
|
30
|
+
.strict()
|
|
31
|
+
.optional(),
|
|
32
|
+
timeout: durationSchema.refine((value) => value > 0, 'Timeout must be positive').optional(),
|
|
33
|
+
})
|
|
34
|
+
.strict();
|
|
35
|
+
/** 应用级单实例调度器,拥有执行代际、状态及数据库生命周期。 */
|
|
36
|
+
export class TaskService {
|
|
37
|
+
storage;
|
|
38
|
+
config;
|
|
39
|
+
logger;
|
|
40
|
+
registrations = new Map();
|
|
5
41
|
running = new Map();
|
|
42
|
+
locks = new Set();
|
|
43
|
+
subscribers = new Set();
|
|
44
|
+
cancelTimer;
|
|
45
|
+
sweep;
|
|
46
|
+
queued = false;
|
|
47
|
+
alive = false;
|
|
48
|
+
constructor(storage, config, logger) {
|
|
49
|
+
this.storage = storage;
|
|
50
|
+
this.config = config;
|
|
51
|
+
this.logger = logger;
|
|
52
|
+
}
|
|
53
|
+
start() {
|
|
54
|
+
const now = Date.now();
|
|
55
|
+
const db = this.storage.db;
|
|
56
|
+
db.exec('BEGIN IMMEDIATE');
|
|
57
|
+
try {
|
|
58
|
+
db.prepare("UPDATE task_attempts SET outcome = 'interrupted', finished_at = ? WHERE outcome = 'running'").run(now);
|
|
59
|
+
db.prepare("UPDATE tasks SET state = 'cancelled', finished_at = ?, updated_at = ? WHERE state = 'cancelling' AND cancel_reason IN ('user', 'superseded')").run(now, now);
|
|
60
|
+
db.prepare("UPDATE tasks SET state = 'pending', next_run_at = ?, updated_at = ?, cancel_reason = NULL WHERE state IN ('running', 'cancelling')").run(now, now);
|
|
61
|
+
db.exec('COMMIT');
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
db.exec('ROLLBACK');
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
this.alive = true;
|
|
68
|
+
this.clean();
|
|
69
|
+
this.sweep = setInterval(() => {
|
|
70
|
+
try {
|
|
71
|
+
this.clean();
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
this.logger.error({ error: this.errorText(error) }, 'Task history cleanup failed');
|
|
75
|
+
}
|
|
76
|
+
}, 60_000);
|
|
77
|
+
this.sweep.unref();
|
|
78
|
+
}
|
|
79
|
+
stop() {
|
|
80
|
+
if (!this.alive)
|
|
81
|
+
return;
|
|
82
|
+
for (const registration of this.registrations.values())
|
|
83
|
+
this.unregister(registration);
|
|
84
|
+
this.alive = false;
|
|
85
|
+
this.cancelTimer?.();
|
|
86
|
+
clearInterval(this.sweep);
|
|
87
|
+
this.subscribers.clear();
|
|
88
|
+
}
|
|
89
|
+
register(plugin, name, handler, options) {
|
|
90
|
+
if (!name.trim())
|
|
91
|
+
throw new TypeError('Task name must not be empty');
|
|
92
|
+
const key = identity(plugin, name);
|
|
93
|
+
if (this.registrations.has(key))
|
|
94
|
+
throw new Error(`Task "${name}" is already registered`);
|
|
95
|
+
const parsed = policySchema.parse(options);
|
|
96
|
+
const policy = {
|
|
97
|
+
maxRetries: parsed.retry?.maxRetries ?? 0,
|
|
98
|
+
delay: parsed.retry?.delay ?? 5_000,
|
|
99
|
+
maxDelay: parsed.retry?.maxDelay ?? 300_000,
|
|
100
|
+
...(parsed.timeout === undefined ? {} : { timeout: parsed.timeout }),
|
|
101
|
+
};
|
|
102
|
+
if (policy.maxDelay < policy.delay)
|
|
103
|
+
throw new TypeError('maxDelay must not be less than delay');
|
|
104
|
+
const registration = { plugin, name, handler, policy, active: false };
|
|
105
|
+
this.registrations.set(key, registration);
|
|
106
|
+
return registration;
|
|
107
|
+
}
|
|
108
|
+
activate(registrations) {
|
|
109
|
+
for (const registration of registrations)
|
|
110
|
+
registration.active = true;
|
|
111
|
+
this.changed();
|
|
112
|
+
}
|
|
113
|
+
unregister(registration) {
|
|
114
|
+
if (this.registrations.get(identity(registration.plugin, registration.name)) !== registration)
|
|
115
|
+
return;
|
|
116
|
+
this.registrations.delete(identity(registration.plugin, registration.name));
|
|
117
|
+
registration.active = false;
|
|
118
|
+
for (const execution of this.running.values()) {
|
|
119
|
+
if (execution.registration !== registration || execution.detached || execution.persisted)
|
|
120
|
+
continue;
|
|
121
|
+
execution.detached = true;
|
|
122
|
+
execution.cancelTimeout?.();
|
|
123
|
+
execution.releasePersistence?.();
|
|
124
|
+
const now = Date.now();
|
|
125
|
+
const cancelled = execution.reason === 'user' || execution.reason === 'superseded';
|
|
126
|
+
this.storage.db
|
|
127
|
+
.prepare('UPDATE task_attempts SET outcome = ?, finished_at = ? WHERE id = ?')
|
|
128
|
+
.run(cancelled ? 'cancelled' : 'interrupted', now, execution.attemptId);
|
|
129
|
+
this.storage.db
|
|
130
|
+
.prepare('UPDATE tasks SET state = ?, next_run_at = ?, updated_at = ?, finished_at = ?, cancel_reason = NULL WHERE id = ?')
|
|
131
|
+
.run(cancelled ? 'cancelled' : 'pending', now, now, cancelled ? now : null, execution.task.id);
|
|
132
|
+
execution.reason = 'interrupted';
|
|
133
|
+
execution.controller.abort(new DOMException('Plugin unloaded', 'AbortError'));
|
|
134
|
+
}
|
|
135
|
+
this.changed();
|
|
136
|
+
}
|
|
137
|
+
schedule(registration, payload, options) {
|
|
138
|
+
if ((options.at === undefined) === (options.delay === undefined))
|
|
139
|
+
throw new TypeError('必须且只能指定 at 或 delay');
|
|
140
|
+
const runAt = options.at === undefined
|
|
141
|
+
? Date.now() + parseDuration(options.delay)
|
|
142
|
+
: Number(options.at);
|
|
143
|
+
if (!Number.isFinite(runAt))
|
|
144
|
+
throw new TypeError('无效的任务时间');
|
|
145
|
+
const json = JSON.stringify(payload);
|
|
146
|
+
if (json === undefined)
|
|
147
|
+
throw new TypeError('任务 payload 必须可以序列化为 JSON');
|
|
148
|
+
const key = options.key ?? randomUUID();
|
|
149
|
+
for (const previous of this.storage.db
|
|
150
|
+
.prepare("SELECT id FROM tasks WHERE plugin = ? AND name = ? AND key = ? AND state IN ('pending', 'running', 'retry_wait', 'cancelling')")
|
|
151
|
+
.all(registration.plugin, registration.name, key))
|
|
152
|
+
this.cancel(String(previous.id), 'superseded');
|
|
153
|
+
const now = Date.now();
|
|
154
|
+
const id = randomUUID();
|
|
155
|
+
this.storage.db
|
|
156
|
+
.prepare('INSERT INTO tasks (id, plugin, name, key, payload, state, run_at, next_run_at, created_at, updated_at, policy) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)')
|
|
157
|
+
.run(id, registration.plugin, registration.name, key, json, 'pending', Math.trunc(runAt), Math.trunc(runAt), now, now, JSON.stringify(registration.policy));
|
|
158
|
+
this.changed(id);
|
|
159
|
+
return key;
|
|
160
|
+
}
|
|
161
|
+
get(id) {
|
|
162
|
+
const row = this.storage.db.prepare('SELECT * FROM tasks WHERE id = ?').get(id);
|
|
163
|
+
return row ? this.record(row) : undefined;
|
|
164
|
+
}
|
|
165
|
+
latest(plugin, name, key) {
|
|
166
|
+
const row = this.storage.db
|
|
167
|
+
.prepare('SELECT * FROM tasks WHERE plugin = ? AND name = ? AND key = ? ORDER BY rowid DESC LIMIT 1')
|
|
168
|
+
.get(plugin, name, key);
|
|
169
|
+
return row ? this.record(row) : undefined;
|
|
170
|
+
}
|
|
171
|
+
query(options = {}) {
|
|
172
|
+
const conditions = [];
|
|
173
|
+
const values = [];
|
|
174
|
+
for (const [column, value] of [
|
|
175
|
+
['plugin', options.plugin],
|
|
176
|
+
['name', options.name],
|
|
177
|
+
['state', options.state],
|
|
178
|
+
]) {
|
|
179
|
+
if (value !== undefined) {
|
|
180
|
+
conditions.push(`${column} = ?`);
|
|
181
|
+
values.push(value);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
if (options.q) {
|
|
185
|
+
conditions.push('(instr(key, ?) > 0 OR instr(name, ?) > 0 OR instr(plugin, ?) > 0)');
|
|
186
|
+
values.push(options.q, options.q, options.q);
|
|
187
|
+
}
|
|
188
|
+
const where = conditions.length ? `WHERE ${conditions.join(' AND ')}` : '';
|
|
189
|
+
const total = Number(this.storage.db.prepare(`SELECT COUNT(*) AS total FROM tasks ${where}`).get(...values)?.total);
|
|
190
|
+
const rows = this.storage.db
|
|
191
|
+
.prepare(`SELECT * FROM tasks ${where} ORDER BY created_at DESC, rowid DESC LIMIT ? OFFSET ?`)
|
|
192
|
+
.all(...values, options.limit ?? 50, options.offset ?? 0);
|
|
193
|
+
return { items: rows.map((row) => this.record(row)), total };
|
|
194
|
+
}
|
|
195
|
+
list(plugin, name) {
|
|
196
|
+
return this.storage.db
|
|
197
|
+
.prepare("SELECT * FROM tasks WHERE plugin = ? AND name = ? AND state IN ('pending', 'running', 'retry_wait', 'cancelling') ORDER BY run_at, key")
|
|
198
|
+
.all(plugin, name)
|
|
199
|
+
.map((row) => this.record(row));
|
|
200
|
+
}
|
|
201
|
+
attempts(taskId) {
|
|
202
|
+
return this.storage.db
|
|
203
|
+
.prepare('SELECT * FROM task_attempts WHERE task_id = ? ORDER BY attempt DESC')
|
|
204
|
+
.all(taskId)
|
|
205
|
+
.map((row) => ({
|
|
206
|
+
id: String(row.id),
|
|
207
|
+
taskId,
|
|
208
|
+
attempt: Number(row.attempt),
|
|
209
|
+
startedAt: Number(row.started_at),
|
|
210
|
+
...(row.finished_at === null ? {} : { finishedAt: Number(row.finished_at) }),
|
|
211
|
+
outcome: row.outcome,
|
|
212
|
+
...(row.error === null ? {} : { error: String(row.error) }),
|
|
213
|
+
deliveryFailure: row.delivery_failure === null
|
|
214
|
+
? undefined
|
|
215
|
+
: JSON.parse(String(row.delivery_failure)),
|
|
216
|
+
}));
|
|
217
|
+
}
|
|
218
|
+
retry(id, options) {
|
|
219
|
+
const task = this.get(id);
|
|
220
|
+
if (!task?.canRetry)
|
|
221
|
+
throw new TaskConflictError('任务必须处于失败状态,且处理器已激活');
|
|
222
|
+
if (task.deliveryFailure && task.deliveryFailure.outcome !== 'not_sent' && !options?.confirmDelivery)
|
|
223
|
+
throw new TaskConflictError('请先核对已发送的消息,再确认重试');
|
|
224
|
+
const now = Date.now();
|
|
225
|
+
this.storage.db
|
|
226
|
+
.prepare("UPDATE tasks SET state = 'pending', failures = 0, next_run_at = ?, updated_at = ?, finished_at = NULL, cancel_reason = NULL WHERE id = ? AND state = 'failed'")
|
|
227
|
+
.run(now, now, id);
|
|
228
|
+
this.changed(id);
|
|
229
|
+
return this.get(id);
|
|
230
|
+
}
|
|
231
|
+
cancel(id, reason = 'user') {
|
|
232
|
+
const task = this.get(id);
|
|
233
|
+
if (!task || terminal.has(task.state))
|
|
234
|
+
return false;
|
|
235
|
+
const now = Date.now();
|
|
236
|
+
const execution = this.running.get(id);
|
|
237
|
+
if (task.state === 'cancelling' && execution?.reason !== 'timeout')
|
|
238
|
+
return false;
|
|
239
|
+
const running = execution !== undefined && !execution.detached;
|
|
240
|
+
this.storage.db
|
|
241
|
+
.prepare('UPDATE tasks SET state = ?, cancel_reason = ?, updated_at = ?, finished_at = ? WHERE id = ?')
|
|
242
|
+
.run(running ? 'cancelling' : 'cancelled', reason, now, running ? null : now, id);
|
|
243
|
+
if (running) {
|
|
244
|
+
execution.reason = reason;
|
|
245
|
+
execution.cancelTimeout?.();
|
|
246
|
+
execution.controller.abort(new DOMException('Task cancelled', 'AbortError'));
|
|
247
|
+
}
|
|
248
|
+
this.changed(id);
|
|
249
|
+
return true;
|
|
250
|
+
}
|
|
251
|
+
subscribe(listener) {
|
|
252
|
+
this.subscribers.add(listener);
|
|
253
|
+
return () => this.subscribers.delete(listener);
|
|
254
|
+
}
|
|
255
|
+
clean(now = Date.now()) {
|
|
256
|
+
const db = this.storage.db;
|
|
257
|
+
db.exec('BEGIN IMMEDIATE');
|
|
258
|
+
try {
|
|
259
|
+
db.prepare("DELETE FROM tasks WHERE state IN ('succeeded', 'failed', 'cancelled') AND finished_at < ?").run(now - this.config.tasks.historyRetention);
|
|
260
|
+
db.prepare("DELETE FROM tasks WHERE id IN (SELECT id FROM tasks WHERE state IN ('succeeded', 'failed', 'cancelled') ORDER BY finished_at DESC, rowid DESC LIMIT -1 OFFSET ?)").run(this.config.tasks.maxHistory);
|
|
261
|
+
db.exec('DELETE FROM task_attempts WHERE task_id NOT IN (SELECT id FROM tasks)');
|
|
262
|
+
db.exec('COMMIT');
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
db.exec('ROLLBACK');
|
|
266
|
+
throw error;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
record(row) {
|
|
270
|
+
const registration = this.registrations.get(identity(String(row.plugin), String(row.name)));
|
|
271
|
+
const state = row.state;
|
|
272
|
+
const waiting = state === 'pending' || state === 'retry_wait';
|
|
273
|
+
const blockedReason = !registration?.active
|
|
274
|
+
? '任务处理器未激活'
|
|
275
|
+
: waiting && this.locks.has(identity(String(row.plugin), String(row.name), String(row.key)))
|
|
276
|
+
? '等待同键的上一次执行结束'
|
|
277
|
+
: undefined;
|
|
278
|
+
return {
|
|
279
|
+
id: String(row.id),
|
|
280
|
+
plugin: String(row.plugin),
|
|
281
|
+
name: String(row.name),
|
|
282
|
+
key: String(row.key),
|
|
283
|
+
payload: JSON.parse(String(row.payload)),
|
|
284
|
+
state,
|
|
285
|
+
runAt: Number(row.run_at),
|
|
286
|
+
nextRunAt: Number(row.next_run_at),
|
|
287
|
+
createdAt: Number(row.created_at),
|
|
288
|
+
updatedAt: Number(row.updated_at),
|
|
289
|
+
attempt: Number(row.attempt),
|
|
290
|
+
failures: Number(row.failures),
|
|
291
|
+
policy: JSON.parse(String(row.policy)),
|
|
292
|
+
...(row.started_at === null ? {} : { startedAt: Number(row.started_at) }),
|
|
293
|
+
...(row.finished_at === null ? {} : { finishedAt: Number(row.finished_at) }),
|
|
294
|
+
...(row.error === null ? {} : { error: String(row.error) }),
|
|
295
|
+
deliveryFailure: row.delivery_failure === null
|
|
296
|
+
? undefined
|
|
297
|
+
: JSON.parse(String(row.delivery_failure)),
|
|
298
|
+
...(blockedReason === undefined || terminal.has(state) ? {} : { blockedReason }),
|
|
299
|
+
canRetry: state === 'failed' &&
|
|
300
|
+
registration?.active === true &&
|
|
301
|
+
!this.locks.has(identity(String(row.plugin), String(row.name), String(row.key))) &&
|
|
302
|
+
!this.storage.db
|
|
303
|
+
.prepare("SELECT 1 FROM tasks WHERE plugin = ? AND name = ? AND key = ? AND state IN ('pending', 'running', 'retry_wait', 'cancelling') LIMIT 1")
|
|
304
|
+
.get(String(row.plugin), String(row.name), String(row.key)),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
changed(id) {
|
|
308
|
+
for (const subscriber of this.subscribers) {
|
|
309
|
+
try {
|
|
310
|
+
subscriber(id);
|
|
311
|
+
}
|
|
312
|
+
catch (error) {
|
|
313
|
+
this.logger.error({ error: this.errorText(error) }, 'Task subscriber failed');
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
this.wake();
|
|
317
|
+
}
|
|
318
|
+
wake() {
|
|
319
|
+
if (!this.alive || this.queued)
|
|
320
|
+
return;
|
|
321
|
+
this.queued = true;
|
|
322
|
+
queueMicrotask(() => {
|
|
323
|
+
this.queued = false;
|
|
324
|
+
if (!this.alive)
|
|
325
|
+
return;
|
|
326
|
+
try {
|
|
327
|
+
this.pump();
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
this.logger.error({ error: this.errorText(error) }, 'Task scheduler failed');
|
|
331
|
+
this.cancelTimer = scheduleTimeout(1_000, () => this.wake(), true);
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
pump() {
|
|
336
|
+
this.cancelTimer?.();
|
|
337
|
+
this.cancelTimer = undefined;
|
|
338
|
+
if (this.running.size >= this.config.tasks.maxConcurrent)
|
|
339
|
+
return;
|
|
340
|
+
const rows = this.storage.db
|
|
341
|
+
.prepare("SELECT * FROM tasks WHERE state IN ('pending', 'retry_wait') ORDER BY next_run_at, created_at, rowid")
|
|
342
|
+
.all();
|
|
343
|
+
let next = Number.POSITIVE_INFINITY;
|
|
344
|
+
for (const row of rows) {
|
|
345
|
+
if (this.running.size >= this.config.tasks.maxConcurrent)
|
|
346
|
+
break;
|
|
347
|
+
const task = this.record(row);
|
|
348
|
+
const registration = this.registrations.get(identity(task.plugin, task.name));
|
|
349
|
+
if (!registration?.active || this.locks.has(identity(task.plugin, task.name, task.key)))
|
|
350
|
+
continue;
|
|
351
|
+
if (task.nextRunAt > Date.now()) {
|
|
352
|
+
next = Math.min(next, task.nextRunAt);
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
this.execute(task, registration);
|
|
356
|
+
}
|
|
357
|
+
if (Number.isFinite(next) && this.running.size < this.config.tasks.maxConcurrent)
|
|
358
|
+
this.cancelTimer = scheduleTimeout(Math.min(2_147_483_647, Math.max(0, next - Date.now())), () => this.wake(), true);
|
|
359
|
+
}
|
|
360
|
+
execute(task, registration) {
|
|
361
|
+
const now = Date.now();
|
|
362
|
+
const attemptId = randomUUID();
|
|
363
|
+
const db = this.storage.db;
|
|
364
|
+
db.exec('BEGIN IMMEDIATE');
|
|
365
|
+
try {
|
|
366
|
+
db.prepare("UPDATE tasks SET state = 'running', attempt = attempt + 1, started_at = ?, updated_at = ?, error = NULL, delivery_failure = NULL WHERE id = ?").run(now, now, task.id);
|
|
367
|
+
db.prepare("INSERT INTO task_attempts (id, task_id, plugin, attempt, started_at, outcome) VALUES (?, ?, ?, ?, ?, 'running')").run(attemptId, task.id, task.plugin, task.attempt + 1, now);
|
|
368
|
+
db.exec('COMMIT');
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
db.exec('ROLLBACK');
|
|
372
|
+
throw error;
|
|
373
|
+
}
|
|
374
|
+
const execution = {
|
|
375
|
+
task,
|
|
376
|
+
attemptId,
|
|
377
|
+
registration,
|
|
378
|
+
controller: new AbortController(),
|
|
379
|
+
detached: false,
|
|
380
|
+
persisted: false,
|
|
381
|
+
};
|
|
382
|
+
this.running.set(task.id, execution);
|
|
383
|
+
const lock = identity(task.plugin, task.name, task.key);
|
|
384
|
+
this.locks.add(lock);
|
|
385
|
+
if (task.policy.timeout !== undefined)
|
|
386
|
+
execution.cancelTimeout = scheduleTimeout(task.policy.timeout, () => {
|
|
387
|
+
if (!this.alive || execution.detached || execution.reason)
|
|
388
|
+
return;
|
|
389
|
+
execution.reason = 'timeout';
|
|
390
|
+
execution.controller.abort(new DOMException('Task timed out', 'TimeoutError'));
|
|
391
|
+
try {
|
|
392
|
+
this.storage.db
|
|
393
|
+
.prepare("UPDATE tasks SET state = 'cancelling', cancel_reason = 'timeout', updated_at = ? WHERE id = ?")
|
|
394
|
+
.run(Date.now(), task.id);
|
|
395
|
+
}
|
|
396
|
+
catch (error) {
|
|
397
|
+
this.logger.error({ taskId: task.id, error: this.errorText(error) }, 'Failed to persist task timeout');
|
|
398
|
+
}
|
|
399
|
+
this.changed(task.id);
|
|
400
|
+
}, true);
|
|
401
|
+
this.changed(task.id);
|
|
402
|
+
void Promise.resolve()
|
|
403
|
+
.then(() => pluginExecution.run(registration.plugin, () => registration.handler(task.payload, {
|
|
404
|
+
signal: execution.controller.signal,
|
|
405
|
+
taskId: task.id,
|
|
406
|
+
attempt: task.attempt + 1,
|
|
407
|
+
key: task.key,
|
|
408
|
+
runAt: task.runAt,
|
|
409
|
+
})))
|
|
410
|
+
.then(() => this.persistResult(execution), (error) => this.persistResult(execution, { error }))
|
|
411
|
+
.catch((error) => {
|
|
412
|
+
this.logger.error({ taskId: task.id, error: this.errorText(error) }, 'Failed to persist task result');
|
|
413
|
+
})
|
|
414
|
+
.finally(() => {
|
|
415
|
+
execution.cancelTimeout?.();
|
|
416
|
+
this.running.delete(task.id);
|
|
417
|
+
this.locks.delete(lock);
|
|
418
|
+
this.changed(task.id);
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
async persistResult(execution, failure) {
|
|
422
|
+
execution.cancelTimeout?.();
|
|
423
|
+
while (this.alive && !execution.detached) {
|
|
424
|
+
try {
|
|
425
|
+
this.finish(execution, failure);
|
|
426
|
+
execution.persisted = true;
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
this.logger.error({ taskId: execution.task.id, error: this.errorText(error) }, 'Task result persistence failed; retaining execution lock');
|
|
431
|
+
await new Promise((resolve) => {
|
|
432
|
+
const cancel = scheduleTimeout(1000, resolve, true);
|
|
433
|
+
execution.releasePersistence = () => {
|
|
434
|
+
cancel();
|
|
435
|
+
resolve();
|
|
436
|
+
};
|
|
437
|
+
});
|
|
438
|
+
execution.releasePersistence = undefined;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
finish(execution, failure) {
|
|
443
|
+
if (!this.alive || execution.detached)
|
|
444
|
+
return;
|
|
445
|
+
const { task, reason } = execution;
|
|
446
|
+
const now = Date.now();
|
|
447
|
+
const cancelled = reason === 'user' || reason === 'superseded';
|
|
448
|
+
const failed = reason === 'timeout' || failure !== undefined;
|
|
449
|
+
const failures = task.failures + (failed ? 1 : 0);
|
|
450
|
+
const delivery = failure?.error instanceof DeliveryError ? failure.error.publicFailure(this.config) : undefined;
|
|
451
|
+
const safeToRetry = !delivery ||
|
|
452
|
+
(delivery.outcome === 'not_sent' &&
|
|
453
|
+
(delivery.code === 'NO_BOT_ONLINE' || delivery.code === 'RATE_LIMITED'));
|
|
454
|
+
const retry = failed && !cancelled && safeToRetry && failures <= task.policy.maxRetries;
|
|
455
|
+
const savedDelivery = delivery ? JSON.stringify(delivery) : null;
|
|
456
|
+
const error = reason === 'timeout' ? '任务执行超时' : failure ? this.errorText(failure.error) : undefined;
|
|
457
|
+
const state = cancelled ? 'cancelled' : retry ? 'retry_wait' : failed ? 'failed' : 'succeeded';
|
|
458
|
+
const nextRunAt = retry
|
|
459
|
+
? now + Math.min(task.policy.maxDelay, task.policy.delay * 2 ** Math.min(30, failures - 1))
|
|
460
|
+
: task.nextRunAt;
|
|
461
|
+
const db = this.storage.db;
|
|
462
|
+
db.exec('BEGIN IMMEDIATE');
|
|
463
|
+
try {
|
|
464
|
+
db.prepare('UPDATE task_attempts SET outcome = ?, finished_at = ?, error = ?, delivery_failure = ? WHERE id = ?').run(cancelled ? 'cancelled' : reason === 'timeout' ? 'timeout' : failed ? 'failed' : 'succeeded', now, error ?? null, savedDelivery, execution.attemptId);
|
|
465
|
+
db.prepare('UPDATE tasks SET state = ?, failures = ?, next_run_at = ?, updated_at = ?, finished_at = ?, error = ?, delivery_failure = ?, cancel_reason = NULL WHERE id = ?').run(state, failures, nextRunAt, now, terminal.has(state) ? now : null, error ?? null, savedDelivery, task.id);
|
|
466
|
+
db.exec('COMMIT');
|
|
467
|
+
}
|
|
468
|
+
catch (cause) {
|
|
469
|
+
db.exec('ROLLBACK');
|
|
470
|
+
throw cause;
|
|
471
|
+
}
|
|
472
|
+
if (failed)
|
|
473
|
+
this.logger.error({
|
|
474
|
+
plugin: task.plugin,
|
|
475
|
+
task: task.name,
|
|
476
|
+
taskId: task.id,
|
|
477
|
+
attempt: task.attempt + 1,
|
|
478
|
+
error,
|
|
479
|
+
deliveryFailure: delivery,
|
|
480
|
+
}, 'Scheduled task failed');
|
|
481
|
+
}
|
|
482
|
+
errorText(error) {
|
|
483
|
+
return redactText(error instanceof Error ? error.message : String(error), this.config).slice(0, 8_192);
|
|
484
|
+
}
|
|
6
485
|
}
|
|
486
|
+
/** 插件级入口,注册在 setup 成功后激活,卸载时解除注册。 */
|
|
7
487
|
export class PersistentTasks {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
488
|
+
activated = false;
|
|
489
|
+
registrations = [];
|
|
490
|
+
service;
|
|
11
491
|
owner;
|
|
12
|
-
signal;
|
|
13
|
-
logger;
|
|
14
|
-
coordinator;
|
|
15
492
|
assertActive;
|
|
16
|
-
constructor(
|
|
17
|
-
this.
|
|
493
|
+
constructor(service, owner, signal, assertActive) {
|
|
494
|
+
this.service = service;
|
|
18
495
|
this.owner = owner;
|
|
19
|
-
this.signal = signal;
|
|
20
|
-
this.logger = logger;
|
|
21
|
-
this.coordinator = coordinator;
|
|
22
496
|
this.assertActive = assertActive;
|
|
23
497
|
signal.addEventListener('abort', () => {
|
|
24
|
-
for (const
|
|
25
|
-
|
|
26
|
-
timer.cancel();
|
|
27
|
-
this.timers.clear();
|
|
498
|
+
for (const registration of this.registrations)
|
|
499
|
+
service.unregister(registration);
|
|
28
500
|
}, { once: true });
|
|
29
501
|
}
|
|
30
|
-
register(name, handler) {
|
|
502
|
+
register(name, handler, options = {}) {
|
|
31
503
|
this.assertActive();
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
this.
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
const arm = (key, runAt, payload) => {
|
|
38
|
-
entries.get(key)?.cancel();
|
|
39
|
-
const pending = { cancel: () => { } };
|
|
40
|
-
entries.set(key, pending);
|
|
41
|
-
const fire = () => {
|
|
42
|
-
if (this.signal.aborted || entries.get(key) !== pending)
|
|
43
|
-
return;
|
|
44
|
-
const identity = JSON.stringify([this.owner, name, key]);
|
|
45
|
-
const previous = this.coordinator.running.get(identity);
|
|
46
|
-
if (previous) {
|
|
47
|
-
void previous.then(() => {
|
|
48
|
-
if (!this.signal.aborted && entries.get(key) === pending)
|
|
49
|
-
arm(key, runAt, payload);
|
|
50
|
-
});
|
|
51
|
-
return;
|
|
52
|
-
}
|
|
53
|
-
const work = (async () => {
|
|
54
|
-
try {
|
|
55
|
-
await handler(JSON.parse(payload), { signal: this.signal, key, runAt });
|
|
56
|
-
}
|
|
57
|
-
catch (error) {
|
|
58
|
-
this.logger.error({ err: error, task: name, key }, 'Scheduled task failed');
|
|
59
|
-
}
|
|
60
|
-
finally {
|
|
61
|
-
if (!this.signal.aborted && entries.get(key) === pending) {
|
|
62
|
-
try {
|
|
63
|
-
this.storage.db
|
|
64
|
-
.prepare('DELETE FROM scheduled_tasks WHERE plugin = ? AND name = ? AND key = ?')
|
|
65
|
-
.run(this.owner, name, key);
|
|
66
|
-
entries.delete(key);
|
|
67
|
-
}
|
|
68
|
-
catch (error) {
|
|
69
|
-
this.logger.error({ err: error, task: name, key }, 'Failed to remove scheduled task');
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
})();
|
|
74
|
-
this.coordinator.running.set(identity, work);
|
|
75
|
-
void work.finally(() => {
|
|
76
|
-
this.coordinator.running.delete(identity);
|
|
77
|
-
});
|
|
78
|
-
};
|
|
79
|
-
const remaining = Math.max(0, runAt - Date.now());
|
|
80
|
-
pending.cancel = scheduleTimeout(Math.min(remaining, 2_147_483_647), () => {
|
|
81
|
-
if (Date.now() < runAt)
|
|
82
|
-
arm(key, runAt, payload);
|
|
83
|
-
else
|
|
84
|
-
fire();
|
|
85
|
-
}, true);
|
|
86
|
-
};
|
|
87
|
-
const list = () => {
|
|
504
|
+
const registration = this.service.register(this.owner, name, handler, options);
|
|
505
|
+
this.registrations.push(registration);
|
|
506
|
+
if (this.activated)
|
|
507
|
+
this.service.activate([registration]);
|
|
508
|
+
const get = (key) => {
|
|
88
509
|
this.assertActive();
|
|
89
|
-
return this.
|
|
90
|
-
.prepare('SELECT key, run_at, payload FROM scheduled_tasks WHERE plugin = ? AND name = ? ORDER BY run_at, key')
|
|
91
|
-
.all(this.owner, name)
|
|
92
|
-
.map((row) => ({
|
|
93
|
-
key: String(row.key),
|
|
94
|
-
runAt: Number(row.run_at),
|
|
95
|
-
payload: JSON.parse(String(row.payload)),
|
|
96
|
-
}));
|
|
510
|
+
return this.service.latest(this.owner, name, key);
|
|
97
511
|
};
|
|
98
|
-
for (const row of this.storage.db
|
|
99
|
-
.prepare('SELECT key, run_at, payload FROM scheduled_tasks WHERE plugin = ? AND name = ?')
|
|
100
|
-
.all(this.owner, name))
|
|
101
|
-
arm(String(row.key), Number(row.run_at), String(row.payload));
|
|
102
512
|
return {
|
|
103
|
-
schedule: (payload,
|
|
513
|
+
schedule: (payload, settings) => {
|
|
104
514
|
this.assertActive();
|
|
105
|
-
|
|
106
|
-
throw new TypeError('必须且只能指定 at 或 delay');
|
|
107
|
-
const runAt = options.at === undefined
|
|
108
|
-
? Date.now() + parseDuration(options.delay)
|
|
109
|
-
: Number(options.at);
|
|
110
|
-
if (!Number.isFinite(runAt))
|
|
111
|
-
throw new TypeError('无效的任务时间');
|
|
112
|
-
const json = JSON.stringify(payload);
|
|
113
|
-
if (json === undefined)
|
|
114
|
-
throw new TypeError('任务 payload 必须可以序列化为 JSON');
|
|
115
|
-
const key = options.key ?? randomUUID();
|
|
116
|
-
this.storage.db
|
|
117
|
-
.prepare('INSERT INTO scheduled_tasks VALUES (?, ?, ?, ?, ?) ON CONFLICT(plugin, name, key) DO UPDATE SET run_at = excluded.run_at, payload = excluded.payload')
|
|
118
|
-
.run(this.owner, name, key, Math.trunc(runAt), json);
|
|
119
|
-
arm(key, Math.trunc(runAt), json);
|
|
120
|
-
return key;
|
|
515
|
+
return this.service.schedule(registration, payload, settings);
|
|
121
516
|
},
|
|
122
517
|
cancel: (key) => {
|
|
518
|
+
const task = get(key);
|
|
519
|
+
return task ? this.service.cancel(task.id) : false;
|
|
520
|
+
},
|
|
521
|
+
list: () => {
|
|
123
522
|
this.assertActive();
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
return
|
|
523
|
+
return this.service.list(this.owner, name);
|
|
524
|
+
},
|
|
525
|
+
get,
|
|
526
|
+
attempts: (key) => {
|
|
527
|
+
const task = get(key);
|
|
528
|
+
return task ? this.service.attempts(task.id) : [];
|
|
529
|
+
},
|
|
530
|
+
retry: (key, options) => {
|
|
531
|
+
const task = get(key);
|
|
532
|
+
if (!task?.canRetry)
|
|
533
|
+
return false;
|
|
534
|
+
this.service.retry(task.id, options);
|
|
535
|
+
return true;
|
|
130
536
|
},
|
|
131
|
-
list,
|
|
132
537
|
};
|
|
133
538
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
.all(this.owner)) {
|
|
138
|
-
const name = String(row.name);
|
|
139
|
-
if (!this.names.has(name))
|
|
140
|
-
this.logger.warn({ task: name }, 'Scheduled task has no registered handler');
|
|
141
|
-
}
|
|
539
|
+
activate() {
|
|
540
|
+
this.activated = true;
|
|
541
|
+
this.service.activate(this.registrations);
|
|
142
542
|
}
|
|
143
543
|
}
|