@kne/fastify-webhook 0.1.3-alpha.6 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +20 -10
  2. package/index.js +55 -46
  3. package/libs/constants.js +81 -0
  4. package/libs/controllers/_helper.js +16 -0
  5. package/libs/controllers/application.js +73 -0
  6. package/libs/controllers/attempt.js +49 -0
  7. package/libs/controllers/domain.js +40 -0
  8. package/libs/controllers/endpoint.js +90 -0
  9. package/libs/controllers/eventType.js +84 -0
  10. package/libs/controllers/ingest.js +83 -0
  11. package/libs/controllers/mcp.js +41 -0
  12. package/libs/controllers/message.js +56 -0
  13. package/libs/controllers/misc.js +81 -0
  14. package/libs/controllers/operational.js +26 -0
  15. package/libs/controllers/play.js +33 -0
  16. package/libs/controllers/polling.js +48 -0
  17. package/libs/controllers/portal.js +32 -0
  18. package/libs/controllers/public.js +47 -0
  19. package/libs/controllers/stream.js +74 -0
  20. package/libs/helpers/context.js +50 -0
  21. package/libs/models/appPortalSession.js +18 -0
  22. package/libs/models/application.js +21 -0
  23. package/libs/models/attempt.js +36 -0
  24. package/libs/models/channel.js +12 -0
  25. package/libs/models/customDomain.js +15 -0
  26. package/libs/models/endpoint.js +37 -0
  27. package/libs/models/environment.js +13 -0
  28. package/libs/models/eventType.js +22 -0
  29. package/libs/models/idempotency.js +14 -0
  30. package/libs/models/inbox.js +17 -0
  31. package/libs/models/ingestSource.js +17 -0
  32. package/libs/models/ingestToken.js +15 -0
  33. package/libs/models/message.js +27 -0
  34. package/libs/models/operationalSubscription.js +13 -0
  35. package/libs/models/pollingConsumer.js +15 -0
  36. package/libs/models/pollingEndpoint.js +13 -0
  37. package/libs/models/sink.js +20 -0
  38. package/libs/models/stream.js +13 -0
  39. package/libs/models/streamEvent.js +14 -0
  40. package/libs/models/transformation.js +13 -0
  41. package/libs/schema/response.js +120 -0
  42. package/libs/services/appPortal.js +87 -0
  43. package/libs/services/application.js +94 -0
  44. package/libs/services/attempt.js +151 -0
  45. package/libs/services/customDomain.js +87 -0
  46. package/libs/services/delivery.js +297 -0
  47. package/libs/services/endpoint.js +236 -0
  48. package/libs/services/eventType.js +173 -0
  49. package/libs/services/fifo.js +34 -0
  50. package/libs/services/inbound.js +108 -0
  51. package/libs/services/ingest.js +294 -0
  52. package/libs/services/mcp.js +60 -0
  53. package/libs/services/message.js +200 -0
  54. package/libs/services/operational.js +70 -0
  55. package/libs/services/play.js +87 -0
  56. package/libs/services/polling.js +162 -0
  57. package/libs/services/retention.js +66 -0
  58. package/libs/services/scheduler.js +50 -0
  59. package/libs/services/sink.js +67 -0
  60. package/libs/services/stream.js +138 -0
  61. package/libs/services/throttle.js +63 -0
  62. package/libs/services/transform.js +102 -0
  63. package/libs/sinks/index.js +105 -0
  64. package/libs/utils/common.js +184 -0
  65. package/libs/utils/index.js +10 -0
  66. package/libs/utils/outbound.js +114 -0
  67. package/libs/utils/signature.js +160 -0
  68. package/package.json +21 -11
  69. package/libs/controllers/main.js +0 -168
  70. package/libs/models/client.js +0 -58
  71. package/libs/models/example._js +0 -18
  72. package/libs/models/invocation.js +0 -40
  73. package/libs/services/example._js +0 -10
  74. package/libs/services/main.js +0 -172
@@ -0,0 +1,94 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+
5
+ module.exports = fp(async (fastify, options) => {
6
+ const { models, utils, pageParams, tenantWhere, services, Op } = fastify[options.name].context;
7
+
8
+ const normalize = (data, authenticatePayload) => {
9
+ const tenantId = utils.resolveTenantId(authenticatePayload);
10
+ return { ...data, tenantId };
11
+ };
12
+
13
+ const create = async (authenticatePayload, data) => {
14
+ const payload = normalize(data, authenticatePayload);
15
+ if (!payload.name) {
16
+ throw new Error('应用名称不能为空');
17
+ }
18
+ if (payload.uid) {
19
+ const exists = await models.application.findOne({ where: tenantWhere(authenticatePayload, { uid: payload.uid }) });
20
+ if (exists) {
21
+ return exists;
22
+ }
23
+ }
24
+ const record = await models.application.create(payload);
25
+ if (services.operational?.emit) {
26
+ await services.operational.emit(authenticatePayload, 'application.created', { applicationId: record.id, name: record.name });
27
+ }
28
+ return record;
29
+ };
30
+
31
+ const save = async (authenticatePayload, data) => {
32
+ if (!data.id) {
33
+ throw new Error('缺少应用 ID');
34
+ }
35
+ const record = await models.application.findOne({ where: tenantWhere(authenticatePayload, { id: data.id }) });
36
+ if (!record) {
37
+ throw new Error('应用不存在');
38
+ }
39
+ const allowed = ['name', 'description', 'throttleRate', 'status', 'region', 'metadata', 'environmentId'];
40
+ allowed.forEach(key => {
41
+ if (data[key] !== undefined) {
42
+ record[key] = data[key];
43
+ }
44
+ });
45
+ await record.save();
46
+ return record;
47
+ };
48
+
49
+ const remove = async (authenticatePayload, { id }) => {
50
+ if (!id) {
51
+ throw new Error('缺少应用 ID');
52
+ }
53
+ await models.endpoint.destroy({ where: tenantWhere(authenticatePayload, { applicationId: id }) });
54
+ await models.application.destroy({ where: tenantWhere(authenticatePayload, { id }) });
55
+ if (services.operational?.emit) {
56
+ await services.operational.emit(authenticatePayload, 'application.removed', { applicationId: id });
57
+ }
58
+ return {};
59
+ };
60
+
61
+ const detail = async (authenticatePayload, { id, uid }) => {
62
+ const where = tenantWhere(authenticatePayload);
63
+ if (id) {
64
+ where.id = id;
65
+ } else if (uid) {
66
+ where.uid = uid;
67
+ } else {
68
+ throw new Error('必须提供 id 或 uid');
69
+ }
70
+ const record = await models.application.findOne({ where });
71
+ if (!record) {
72
+ throw new Error('应用不存在');
73
+ }
74
+ return record;
75
+ };
76
+
77
+ const list = async (authenticatePayload, params = {}) => {
78
+ const { offset, limit } = pageParams(params);
79
+ const where = tenantWhere(authenticatePayload);
80
+ if (params.name) {
81
+ where.name = { [Op.like]: `%${params.name}%` };
82
+ }
83
+ if (params.status) {
84
+ where.status = params.status;
85
+ }
86
+ if (params.uid) {
87
+ where.uid = params.uid;
88
+ }
89
+ const { count, rows } = await models.application.findAndCountAll({ where, offset, limit, order: [['createdAt', 'DESC']] });
90
+ return { pageData: rows, totalCount: count };
91
+ };
92
+
93
+ fastify[options.name].services.application = { create, save, remove, detail, list, normalize };
94
+ });
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const { generateId } = require('../utils/common');
5
+
6
+ module.exports = fp(async (fastify, options) => {
7
+ const ctx = fastify[options.name].context;
8
+ const { models, utils, pageParams, tenantWhere, Op } = ctx;
9
+
10
+ /** 为一条消息+端点创建待投递记录 */
11
+ const createPending = async (tenantId, message, endpoint) => {
12
+ return models.attempt.create({
13
+ tenantId,
14
+ messageId: message.id,
15
+ endpointId: endpoint.id,
16
+ webhookId: message.uid || generateId('msg'),
17
+ requestHeaders: endpoint.headers || {},
18
+ requestBody: message.rawBody,
19
+ status: 'pending',
20
+ retryCount: 0,
21
+ nextAttemptAt: new Date()
22
+ });
23
+ };
24
+
25
+ const detail = async (authenticatePayload, { id }) => {
26
+ const record = await models.attempt.findOne({ where: tenantWhere(authenticatePayload, { id }) });
27
+ if (!record) {
28
+ throw new Error('投递记录不存在');
29
+ }
30
+ return record;
31
+ };
32
+
33
+ const list = async (authenticatePayload, params = {}) => {
34
+ const { offset, limit } = pageParams(params);
35
+ const where = tenantWhere(authenticatePayload);
36
+ if (params.messageId) {
37
+ where.messageId = params.messageId;
38
+ }
39
+ if (params.endpointId) {
40
+ where.endpointId = params.endpointId;
41
+ }
42
+ if (params.status) {
43
+ where.status = params.status;
44
+ }
45
+ if (params.retryCount !== undefined) {
46
+ where.retryCount = Number(params.retryCount);
47
+ }
48
+ if (params.startTime || params.endTime) {
49
+ where.startAt = {};
50
+ if (params.startTime) {
51
+ where.startAt[Op.gte] = new Date(params.startTime);
52
+ }
53
+ if (params.endTime) {
54
+ where.startAt[Op.lte] = new Date(params.endTime);
55
+ }
56
+ }
57
+ const { count, rows } = await models.attempt.findAndCountAll({ where, offset, limit, order: [['createdAt', 'DESC']] });
58
+ return { pageData: rows, totalCount: count };
59
+ };
60
+
61
+ /** 单条重放:复用原 webhookId,重置重试计数 */
62
+ const resend = async (authenticatePayload, { id }) => {
63
+ const record = await models.attempt.findOne({ where: tenantWhere(authenticatePayload, { id }) });
64
+ if (!record) {
65
+ throw new Error('投递记录不存在');
66
+ }
67
+ record.status = 'pending';
68
+ record.retryCount = 0;
69
+ record.nextAttemptAt = new Date();
70
+ record.responseStatus = null;
71
+ record.responseBody = null;
72
+ record.error = null;
73
+ record.endAt = null;
74
+ record.duration = null;
75
+ await record.save();
76
+
77
+ const message = await models.message.findOne({ where: { tenantId: record.tenantId, id: record.messageId } });
78
+ if (message) {
79
+ message.status = 'pending';
80
+ await message.save();
81
+ }
82
+ return { id: record.id, status: 'pending' };
83
+ };
84
+
85
+ /** 批量恢复失败消息:按起始时间筛选 */
86
+ const recoverFailed = async (authenticatePayload, { startTime, applicationId } = {}) => {
87
+ const tenantId = utils.resolveTenantId(authenticatePayload);
88
+ const where = { tenantId, status: 'failed' };
89
+ if (startTime) {
90
+ where.createdAt = { [Op.gte]: new Date(startTime) };
91
+ }
92
+ if (applicationId) {
93
+ where.applicationId = applicationId;
94
+ }
95
+ const messages = await models.message.findAll({ where });
96
+ let count = 0;
97
+ for (const message of messages) {
98
+ const attempts = await models.attempt.findAll({ where: { tenantId, messageId: message.id, status: 'failed' } });
99
+ for (const attempt of attempts) {
100
+ attempt.status = 'pending';
101
+ attempt.retryCount = 0;
102
+ attempt.nextAttemptAt = new Date();
103
+ attempt.error = null;
104
+ await attempt.save();
105
+ count++;
106
+ }
107
+ message.status = 'pending';
108
+ await message.save();
109
+ }
110
+ return { recovered: count, messages: messages.length };
111
+ };
112
+
113
+ /** 补发从未投递过的消息 */
114
+ const replayMissing = async (authenticatePayload, { startTime, applicationId } = {}) => {
115
+ const tenantId = utils.resolveTenantId(authenticatePayload);
116
+ const where = { tenantId, status: 'success' };
117
+ if (startTime) {
118
+ where.createdAt = { [Op.gte]: new Date(startTime) };
119
+ }
120
+ if (applicationId) {
121
+ where.applicationId = applicationId;
122
+ }
123
+ const messages = await models.message.findAll({ where });
124
+ let count = 0;
125
+ for (const message of messages) {
126
+ const existing = await models.attempt.count({ where: { tenantId, messageId: message.id } });
127
+ if (existing > 0) {
128
+ continue;
129
+ }
130
+ const endpoints = await servicesForReplay().endpoint.findMatching(tenantId, message.applicationId, message);
131
+ for (const endpoint of endpoints) {
132
+ await createPending(tenantId, message, endpoint);
133
+ count++;
134
+ }
135
+ }
136
+ return { replayed: count, messages: messages.length };
137
+ };
138
+
139
+ // 延迟引用 service,避免模块初始化顺序问题
140
+ let lazyServices = null;
141
+ const servicesForReplay = () => lazyServices || (lazyServices = fastify[options.name].services);
142
+
143
+ fastify[options.name].services.attempt = {
144
+ createPending,
145
+ detail,
146
+ list,
147
+ resend,
148
+ recoverFailed,
149
+ replayMissing
150
+ };
151
+ });
@@ -0,0 +1,87 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const dns = require('node:dns/promises');
5
+
6
+ module.exports = fp(async (fastify, options) => {
7
+ const ctx = fastify[options.name].context;
8
+ const { models, utils, pageParams, tenantWhere } = ctx;
9
+
10
+ const cnameTargetFor = service => `${service}.${options.domainBase || 'webhook.example.com'}`;
11
+
12
+ const create = async (authenticatePayload, data) => {
13
+ if (!data.domain || !data.service) {
14
+ throw new Error('domain 与 service 不能为空');
15
+ }
16
+ const tenantId = utils.resolveTenantId(authenticatePayload);
17
+ return models.customDomain.create({
18
+ tenantId,
19
+ service: data.service,
20
+ domain: data.domain,
21
+ region: data.region,
22
+ cnameTarget: cnameTargetFor(data.service),
23
+ status: 'pending',
24
+ tlsStatus: 'pending'
25
+ });
26
+ };
27
+
28
+ /** 验证 CNAME 是否指向目标;验证通过后触发 TLS 签发流程 */
29
+ const verify = async (authenticatePayload, { id }) => {
30
+ const record = await models.customDomain.findOne({ where: tenantWhere(authenticatePayload, { id }) });
31
+ if (!record) {
32
+ throw new Error('自定义域名不存在');
33
+ }
34
+ let resolved = [];
35
+ try {
36
+ resolved = await dns.resolveCname(record.domain);
37
+ } catch {
38
+ try {
39
+ resolved = await dns.resolve4(record.domain);
40
+ } catch {
41
+ resolved = [];
42
+ }
43
+ }
44
+ const matched = resolved.some(item => String(item).toLowerCase() === String(record.cnameTarget).toLowerCase());
45
+ if (matched) {
46
+ record.status = 'verified';
47
+ // TLS 证书签发交由部署层 ACME 完成,此处仅置为 pending/issued 状态
48
+ record.tlsStatus = options.autoIssueTls === false ? 'pending' : 'issued';
49
+ } else {
50
+ record.status = 'failed';
51
+ record.tlsStatus = 'pending';
52
+ }
53
+ await record.save();
54
+ return {
55
+ ...record.get({ plain: true }),
56
+ resolved,
57
+ expected: record.cnameTarget
58
+ };
59
+ };
60
+
61
+ const list = async (authenticatePayload, params = {}) => {
62
+ const { offset, limit } = pageParams(params);
63
+ const { count, rows } = await models.customDomain.findAndCountAll({ where: tenantWhere(authenticatePayload), offset, limit });
64
+ return { pageData: rows, totalCount: count };
65
+ };
66
+
67
+ const remove = async (authenticatePayload, { id }) => {
68
+ await models.customDomain.destroy({ where: tenantWhere(authenticatePayload, { id }) });
69
+ return {};
70
+ };
71
+
72
+ /** 按 service + domain 查找生效配置:租户记录优先,缺失回退全局 */
73
+ const resolve = async (service, domain, authenticatePayload = null) => {
74
+ const tenantId = utils.resolveTenantId(authenticatePayload);
75
+ if (tenantId !== '') {
76
+ const tenantRecord = await models.customDomain.findOne({
77
+ where: { tenantId, service, domain, status: 'verified' }
78
+ });
79
+ if (tenantRecord) {
80
+ return tenantRecord;
81
+ }
82
+ }
83
+ return models.customDomain.findOne({ where: { tenantId: '', service, domain, status: 'verified' } });
84
+ };
85
+
86
+ fastify[options.name].services.customDomain = { create, verify, list, remove, resolve, cnameTargetFor };
87
+ });
@@ -0,0 +1,297 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const {
5
+ DELIVERY_TIMEOUT,
6
+ RETRY_SCHEDULE
7
+ } = require('../constants');
8
+ const {
9
+ MAX_RETRY_COUNT,
10
+ nextRetryDelay,
11
+ parseRetryAfter,
12
+ parseDeliveryControl,
13
+ isSuccessStatus,
14
+ getHeader
15
+ } = require('../utils/common');
16
+ const { signHeaders } = require('../utils/signature');
17
+ const { assertOutboundUrl, sendHttp } = require('../utils/outbound');
18
+
19
+ module.exports = fp(async (fastify, options) => {
20
+ const ctx = fastify[options.name].context;
21
+ const { models, utils, services, Op } = ctx;
22
+
23
+ /** 构造出站请求(签名 + 变换后 payload) */
24
+ const buildRequest = async (attempt, message, endpoint, transformed) => {
25
+ const rawBody = transformed?.body != null ? transformed.body : (attempt.requestBody || message.rawBody || '{}');
26
+ const id = attempt.webhookId || message.uid || message.id?.toString();
27
+ const timestamp = Math.floor(Date.now() / 1000);
28
+ const headers = Object.assign(
29
+ {},
30
+ endpoint.headers || {},
31
+ { 'content-type': 'application/json' },
32
+ signHeaders({ id, timestamp, rawBody, secret: endpoint.secret }),
33
+ transformed?.headers || {}
34
+ );
35
+ return {
36
+ method: transformed?.method || 'POST',
37
+ url: transformed?.url || endpoint.url,
38
+ headers,
39
+ body: rawBody
40
+ };
41
+ };
42
+
43
+ /**
44
+ * 多实例安全抢占:仅当 status 仍为 pending/retrying 时切到 sending。
45
+ * 返回 false 表示已被其它实例抢走。
46
+ */
47
+ const claimAttempt = async (tenantId, attemptId) => {
48
+ const [affected] = await models.attempt.update(
49
+ { status: 'sending', startAt: new Date() },
50
+ {
51
+ where: {
52
+ tenantId,
53
+ id: attemptId,
54
+ status: { [Op.in]: ['pending', 'retrying'] }
55
+ }
56
+ }
57
+ );
58
+ return affected > 0;
59
+ };
60
+
61
+ /**
62
+ * 执行一次投递尝试。
63
+ * @param {string} tenantId
64
+ * @param {number} attemptId
65
+ * @param {object} [override] 覆盖项(如 skipTransform)
66
+ */
67
+ const dispatch = async (tenantId, attemptId, override = {}) => {
68
+ const attempt = await models.attempt.findOne({ where: { tenantId, id: attemptId } });
69
+ if (!attempt || !['pending', 'retrying'].includes(attempt.status)) {
70
+ return { skipped: true };
71
+ }
72
+ const message = await models.message.findOne({ where: { tenantId, id: attempt.messageId } });
73
+ const endpoint = await models.endpoint.findOne({ where: { tenantId, id: attempt.endpointId } });
74
+ if (!message || !endpoint) {
75
+ attempt.status = 'failed';
76
+ attempt.error = '消息或端点不存在';
77
+ await attempt.save();
78
+ return { error: attempt.error };
79
+ }
80
+ if (endpoint.status !== 'active') {
81
+ attempt.status = 'failed';
82
+ attempt.error = '端点未激活';
83
+ await attempt.save();
84
+ return { error: attempt.error };
85
+ }
86
+
87
+ // 平滑限流:等待直到获得投递槽位
88
+ if (services.throttle) {
89
+ const application = await models.application.findOne({ where: { tenantId, id: endpoint.applicationId } });
90
+ await services.throttle.waitForSlot(endpoint, application);
91
+ }
92
+
93
+ // FIFO 端点:同一应用内严格串行,上一条成功后才发下一条
94
+ if (endpoint.kind === 'fifo' && services.fifo) {
95
+ const canProceed = await services.fifo.acquire(attempt);
96
+ if (!canProceed) {
97
+ return { skipped: true, reason: 'fifo-waiting' };
98
+ }
99
+ }
100
+
101
+ if (!(await claimAttempt(tenantId, attemptId))) {
102
+ return { skipped: true, reason: 'claimed-by-other' };
103
+ }
104
+ await attempt.reload();
105
+
106
+ const startAt = attempt.startAt || new Date();
107
+ attempt.retryCount = attempt.retryCount || 0;
108
+ await attempt.save();
109
+
110
+ // 变换脚本
111
+ let transformed = null;
112
+ if (!override.skipTransform && services.transform?.enabled && endpoint.kind !== 'sink') {
113
+ try {
114
+ transformed = await services.transform.runForEndpoint(tenantId, endpoint.id, {
115
+ method: 'POST',
116
+ url: endpoint.url,
117
+ payload: message.payload,
118
+ rawBody: message.rawBody,
119
+ eventType: message.type,
120
+ transformationsParams: {},
121
+ events: [{ payload: message.payload, eventType: message.type }]
122
+ });
123
+ if (transformed?.cancel) {
124
+ attempt.status = 'success';
125
+ attempt.canceled = true;
126
+ attempt.endAt = new Date();
127
+ attempt.duration = attempt.endAt - startAt;
128
+ attempt.responseStatus = 200;
129
+ attempt.responseBody = 'canceled by transformation';
130
+ await attempt.save();
131
+ await services.endpoint.resetFailure(tenantId, endpoint.id);
132
+ await finalizeMessage(tenantId, attempt.messageId);
133
+ return { canceled: true };
134
+ }
135
+ } catch (error) {
136
+ fastify.log?.error?.({ err: error }, 'transformation failed');
137
+ }
138
+ }
139
+
140
+ const request = await buildRequest(attempt, message, endpoint, transformed);
141
+ attempt.requestHeaders = request.headers;
142
+ attempt.requestBody = request.body;
143
+ attempt.transformedBody = request.body;
144
+ await attempt.save();
145
+
146
+ let response;
147
+ let error = null;
148
+ try {
149
+ // 投递前(含变换改写后的 URL)再次做 SSRF 校验
150
+ assertOutboundUrl(request.url, { allowPrivateUrl: options.allowPrivateUrl });
151
+ response = await sendHttp(
152
+ {
153
+ method: request.method,
154
+ url: request.url,
155
+ headers: request.headers,
156
+ body: request.body,
157
+ timeout: DELIVERY_TIMEOUT
158
+ },
159
+ {
160
+ httpClient: options.httpClient,
161
+ allowPrivateUrl: options.allowPrivateUrl,
162
+ skipUrlCheck: true
163
+ }
164
+ );
165
+ } catch (err) {
166
+ error = err?.message || String(err);
167
+ }
168
+
169
+ const endAt = new Date();
170
+ attempt.endAt = endAt;
171
+ attempt.duration = endAt - startAt;
172
+
173
+ const statusCode = response ? response.status : 0;
174
+ const responseHeaders = response ? response.headers || {} : {};
175
+ const rawResponseBody = response ? response.body : '';
176
+ attempt.responseStatus = statusCode || null;
177
+ attempt.responseHeaders = responseHeaders;
178
+ attempt.responseBody = String(rawResponseBody).slice(0, 8192);
179
+ attempt.error = error;
180
+
181
+ // Delivery Control 响应头
182
+ const control = parseDeliveryControl(responseHeaders);
183
+ if (control === 'abort-message') {
184
+ attempt.status = 'success';
185
+ await attempt.save();
186
+ await finalizeMessage(tenantId, attempt.messageId);
187
+ return { aborted: true };
188
+ }
189
+ if (control === 'disable') {
190
+ await services.endpoint.setStatus({ tenantId }, { id: endpoint.id, status: 'disabled', reason: '端点通过响应头请求禁用' });
191
+ }
192
+
193
+ if (!error && isSuccessStatus(statusCode)) {
194
+ attempt.status = 'success';
195
+ attempt.nextAttemptAt = null;
196
+ await attempt.save();
197
+ await services.endpoint.resetFailure(tenantId, endpoint.id);
198
+ await finalizeMessage(tenantId, attempt.messageId);
199
+ if (services.operational?.emit) {
200
+ await services.operational.emit({ tenantId }, 'message.delivered', {
201
+ messageId: attempt.messageId,
202
+ endpointId: endpoint.id,
203
+ attemptId: attempt.id
204
+ });
205
+ }
206
+ return { success: true, attemptId: attempt.id };
207
+ }
208
+
209
+ const retryAfter = parseRetryAfter(getHeader(responseHeaders, 'retry-after'));
210
+ const nextDelay = retryAfter != null ? retryAfter : nextRetryDelay(attempt.retryCount);
211
+ const willRetry = attempt.retryCount + 1 < MAX_RETRY_COUNT;
212
+
213
+ attempt.status = willRetry ? 'retrying' : 'failed';
214
+ attempt.retryCount = attempt.retryCount + 1;
215
+ attempt.nextAttemptAt = willRetry ? new Date(Date.now() + nextDelay) : null;
216
+ await attempt.save();
217
+
218
+ if (!willRetry) {
219
+ if (services.operational?.emit) {
220
+ await services.operational.emit({ tenantId }, 'message.attempt.exhausted', {
221
+ messageId: attempt.messageId,
222
+ endpointId: endpoint.id,
223
+ attemptId: attempt.id
224
+ });
225
+ }
226
+ await finalizeMessage(tenantId, attempt.messageId);
227
+ }
228
+
229
+ await services.endpoint.recordFailure(tenantId, endpoint.id, await getEnvironment(tenantId, message));
230
+ return { success: false, retrying: willRetry, attemptId: attempt.id, nextAttemptAt: attempt.nextAttemptAt };
231
+ };
232
+
233
+ const getEnvironment = async (tenantId, message) => {
234
+ if (message.environmentId) {
235
+ return models.environment.findOne({ where: { tenantId, id: message.environmentId } });
236
+ }
237
+ return models.environment.findOne({ where: { tenantId, region: message.region || 'default' } });
238
+ };
239
+
240
+ /** 消息状态汇总:所有 attempt 终态后确定消息状态 */
241
+ const finalizeMessage = async (tenantId, messageId) => {
242
+ const message = await models.message.findOne({ where: { tenantId, id: messageId } });
243
+ if (!message || message.status === 'aborted') {
244
+ return;
245
+ }
246
+ const counts = await models.attempt.findAll({
247
+ where: { tenantId, messageId },
248
+ attributes: ['status', [ctx.Sequelize.fn('COUNT', ctx.Sequelize.col('id')), 'count']],
249
+ group: ['status'],
250
+ raw: true
251
+ });
252
+ const map = {};
253
+ counts.forEach(item => {
254
+ map[item.status] = Number(item.count);
255
+ });
256
+ const active = (map.pending || 0) + (map.sending || 0) + (map.retrying || 0);
257
+ if (active > 0) {
258
+ message.status = 'sending';
259
+ } else if ((map.failed || 0) > 0 && (map.success || 0) === 0) {
260
+ message.status = 'failed';
261
+ } else {
262
+ message.status = 'success';
263
+ }
264
+ await message.save();
265
+
266
+ const environment = await getEnvironment(tenantId, message);
267
+ if (message.status === 'success' && environment?.settings?.retentionPolicy === 'delete-on-delivery') {
268
+ await services.message.purgePayload(message.id);
269
+ }
270
+ };
271
+
272
+ /** 调度器 tick:取出所有到期的 attempt 执行 */
273
+ const runDue = async (limit = 100) => {
274
+ const due = await models.attempt.findAll({
275
+ where: {
276
+ status: { [Op.in]: ['pending', 'retrying'] },
277
+ nextAttemptAt: { [Op.lte]: new Date() }
278
+ },
279
+ order: [['nextAttemptAt', 'ASC']],
280
+ limit
281
+ });
282
+ const results = [];
283
+ for (const attempt of due) {
284
+ results.push(await dispatch(attempt.tenantId, attempt.id));
285
+ }
286
+ return { processed: results.length, results };
287
+ };
288
+
289
+ fastify[options.name].services.delivery = {
290
+ dispatch,
291
+ runDue,
292
+ buildRequest,
293
+ finalizeMessage,
294
+ claimAttempt,
295
+ RETRY_SCHEDULE
296
+ };
297
+ });