@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.
- package/README.md +20 -10
- package/index.js +55 -46
- package/libs/constants.js +81 -0
- package/libs/controllers/_helper.js +16 -0
- package/libs/controllers/application.js +73 -0
- package/libs/controllers/attempt.js +49 -0
- package/libs/controllers/domain.js +40 -0
- package/libs/controllers/endpoint.js +90 -0
- package/libs/controllers/eventType.js +84 -0
- package/libs/controllers/ingest.js +83 -0
- package/libs/controllers/mcp.js +41 -0
- package/libs/controllers/message.js +56 -0
- package/libs/controllers/misc.js +81 -0
- package/libs/controllers/operational.js +26 -0
- package/libs/controllers/play.js +33 -0
- package/libs/controllers/polling.js +48 -0
- package/libs/controllers/portal.js +32 -0
- package/libs/controllers/public.js +47 -0
- package/libs/controllers/stream.js +74 -0
- package/libs/helpers/context.js +50 -0
- package/libs/models/appPortalSession.js +18 -0
- package/libs/models/application.js +21 -0
- package/libs/models/attempt.js +36 -0
- package/libs/models/channel.js +12 -0
- package/libs/models/customDomain.js +15 -0
- package/libs/models/endpoint.js +37 -0
- package/libs/models/environment.js +13 -0
- package/libs/models/eventType.js +22 -0
- package/libs/models/idempotency.js +14 -0
- package/libs/models/inbox.js +17 -0
- package/libs/models/ingestSource.js +17 -0
- package/libs/models/ingestToken.js +15 -0
- package/libs/models/message.js +27 -0
- package/libs/models/operationalSubscription.js +13 -0
- package/libs/models/pollingConsumer.js +15 -0
- package/libs/models/pollingEndpoint.js +13 -0
- package/libs/models/sink.js +20 -0
- package/libs/models/stream.js +13 -0
- package/libs/models/streamEvent.js +14 -0
- package/libs/models/transformation.js +13 -0
- package/libs/schema/response.js +120 -0
- package/libs/services/appPortal.js +87 -0
- package/libs/services/application.js +94 -0
- package/libs/services/attempt.js +151 -0
- package/libs/services/customDomain.js +87 -0
- package/libs/services/delivery.js +297 -0
- package/libs/services/endpoint.js +236 -0
- package/libs/services/eventType.js +173 -0
- package/libs/services/fifo.js +34 -0
- package/libs/services/inbound.js +108 -0
- package/libs/services/ingest.js +294 -0
- package/libs/services/mcp.js +60 -0
- package/libs/services/message.js +200 -0
- package/libs/services/operational.js +70 -0
- package/libs/services/play.js +87 -0
- package/libs/services/polling.js +162 -0
- package/libs/services/retention.js +66 -0
- package/libs/services/scheduler.js +50 -0
- package/libs/services/sink.js +67 -0
- package/libs/services/stream.js +138 -0
- package/libs/services/throttle.js +63 -0
- package/libs/services/transform.js +102 -0
- package/libs/sinks/index.js +105 -0
- package/libs/utils/common.js +184 -0
- package/libs/utils/index.js +10 -0
- package/libs/utils/outbound.js +114 -0
- package/libs/utils/signature.js +160 -0
- package/package.json +21 -11
- package/libs/controllers/main.js +0 -168
- package/libs/models/client.js +0 -58
- package/libs/models/example._js +0 -18
- package/libs/models/invocation.js +0 -40
- package/libs/services/example._js +0 -10
- package/libs/services/main.js +0 -172
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { generateToken, getHeader } = require('../utils/common');
|
|
5
|
+
const { signHeaders, generateSecret } = require('../utils/signature');
|
|
6
|
+
|
|
7
|
+
module.exports = fp(async (fastify, options) => {
|
|
8
|
+
const ctx = fastify[options.name].context;
|
|
9
|
+
const { utils } = ctx;
|
|
10
|
+
|
|
11
|
+
// Play token 配置存储在内存中(调试器为无状态工具,进程重启即失效)
|
|
12
|
+
const stores = new Map();
|
|
13
|
+
|
|
14
|
+
const generate = () => {
|
|
15
|
+
const token = generateToken(16);
|
|
16
|
+
stores.set(token, {
|
|
17
|
+
forceStatusCode: null,
|
|
18
|
+
randomFailureRate: 0,
|
|
19
|
+
echoBody: true,
|
|
20
|
+
signingSecret: null,
|
|
21
|
+
history: []
|
|
22
|
+
});
|
|
23
|
+
return { token };
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const getConfig = token => {
|
|
27
|
+
if (!stores.has(token)) {
|
|
28
|
+
stores.set(token, { forceStatusCode: null, randomFailureRate: 0, echoBody: true, signingSecret: null, history: [] });
|
|
29
|
+
}
|
|
30
|
+
return stores.get(token);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const configure = (token, config) => {
|
|
34
|
+
const current = getConfig(token);
|
|
35
|
+
['forceStatusCode', 'randomFailureRate', 'echoBody', 'signingSecret'].forEach(key => {
|
|
36
|
+
if (config[key] !== undefined) {
|
|
37
|
+
current[key] = config[key];
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
return { ...current, history: undefined };
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/** 接收任意请求,返回可配置的状态码并记录历史 */
|
|
44
|
+
const inbound = (token, request, reply) => {
|
|
45
|
+
const config = getConfig(token);
|
|
46
|
+
const rawBody = Buffer.isBuffer(request.rawBody) ? request.rawBody.toString('utf8') : String(request.rawBody || '');
|
|
47
|
+
const statusCode = config.forceStatusCode || (Math.random() < config.randomFailureRate ? 500 : 200);
|
|
48
|
+
const historyItem = {
|
|
49
|
+
id: config.history.length ? config.history[0].id + 1 : 1,
|
|
50
|
+
method: request.method,
|
|
51
|
+
url: request.url,
|
|
52
|
+
headers: request.headers,
|
|
53
|
+
body: rawBody,
|
|
54
|
+
statusCode,
|
|
55
|
+
timestamp: new Date().toISOString()
|
|
56
|
+
};
|
|
57
|
+
config.history.unshift(historyItem);
|
|
58
|
+
if (config.history.length > 500) {
|
|
59
|
+
config.history.length = 500;
|
|
60
|
+
}
|
|
61
|
+
const responseHeaders = config.signingSecret
|
|
62
|
+
? signHeaders({ id: `play_${historyItem.id}`, rawBody, secret: config.signingSecret })
|
|
63
|
+
: {};
|
|
64
|
+
reply.code(statusCode);
|
|
65
|
+
return {
|
|
66
|
+
status: statusCode,
|
|
67
|
+
body: config.echoBody ? { body: rawBody, headers: request.headers } : undefined,
|
|
68
|
+
headers: responseHeaders
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
const history = (token, { iterator, limit = 50 } = {}) => {
|
|
73
|
+
const config = getConfig(token);
|
|
74
|
+
let items = config.history;
|
|
75
|
+
if (iterator) {
|
|
76
|
+
items = items.filter(item => item.id < Number(iterator));
|
|
77
|
+
}
|
|
78
|
+
return { data: items.slice(0, Number(limit)), nextIterator: items.length > Number(limit) ? items[Number(limit) - 1].id : null };
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
const clearHistory = token => {
|
|
82
|
+
getConfig(token).history = [];
|
|
83
|
+
return {};
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
fastify[options.name].services.play = { generate, getConfig, configure, inbound, history, clearHistory, generateSecret };
|
|
87
|
+
});
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { safeEqual } = require('../utils/signature');
|
|
5
|
+
|
|
6
|
+
const LEASE_DURATION = 60 * 1000; // 60 秒租约
|
|
7
|
+
|
|
8
|
+
/** Snowflake / BIGINT offset 不能走 Number(会丢精度),统一用十进制字符串 + BigInt 比较 */
|
|
9
|
+
const toOffset = value => {
|
|
10
|
+
if (value == null || value === '') {
|
|
11
|
+
return '0';
|
|
12
|
+
}
|
|
13
|
+
const text = String(value).trim();
|
|
14
|
+
return /^-?\d+$/.test(text) ? text : '0';
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const compareOffset = (left, right) => {
|
|
18
|
+
const a = BigInt(toOffset(left));
|
|
19
|
+
const b = BigInt(toOffset(right));
|
|
20
|
+
if (a < b) return -1;
|
|
21
|
+
if (a > b) return 1;
|
|
22
|
+
return 0;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const minOffset = (left, right) => (compareOffset(left, right) <= 0 ? toOffset(left) : toOffset(right));
|
|
26
|
+
|
|
27
|
+
module.exports = fp(async (fastify, options) => {
|
|
28
|
+
const ctx = fastify[options.name].context;
|
|
29
|
+
const { models, utils, Op, services } = ctx;
|
|
30
|
+
|
|
31
|
+
/** 创建 Polling 端点凭证,返回 URL 与 API Key(仅此一次明文) */
|
|
32
|
+
const createCredentials = async (authenticatePayload, endpointId) => {
|
|
33
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
34
|
+
const urlToken = utils.generateToken();
|
|
35
|
+
const apiKey = utils.generateToken();
|
|
36
|
+
// paranoid 软删仍占唯一索引,轮换凭证必须硬删
|
|
37
|
+
await models.pollingEndpoint.destroy({ where: { tenantId, endpointId }, force: true });
|
|
38
|
+
await models.pollingEndpoint.create({
|
|
39
|
+
tenantId,
|
|
40
|
+
endpointId,
|
|
41
|
+
tokenHash: utils.hashToken(urlToken),
|
|
42
|
+
apiKeyHash: utils.hashToken(apiKey),
|
|
43
|
+
status: 'active'
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
url: `${options.publicPrefix || '/api/v1/webhook'}/polling/${urlToken}`,
|
|
47
|
+
apiKey
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** consumer 拉取消息:带 offset 与租约,租约过期前未提交会重复返回 */
|
|
52
|
+
const consume = async ({ token, apiKey, consumerId, batchSize = 100 }) => {
|
|
53
|
+
const credentials = await models.pollingEndpoint.findOne({ where: { tokenHash: utils.hashToken(token), status: 'active' } });
|
|
54
|
+
if (!credentials || !safeEqual(credentials.apiKeyHash, utils.hashToken(apiKey || ''))) {
|
|
55
|
+
const error = new Error('Polling 凭证无效');
|
|
56
|
+
error.statusCode = 401;
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
if (!consumerId) {
|
|
60
|
+
const error = new Error('consumerId 不能为空');
|
|
61
|
+
error.statusCode = 400;
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let consumer = await models.pollingConsumer.findOne({
|
|
66
|
+
where: { tenantId: credentials.tenantId, endpointId: credentials.endpointId, consumerId }
|
|
67
|
+
});
|
|
68
|
+
if (!consumer) {
|
|
69
|
+
consumer = await models.pollingConsumer.create({
|
|
70
|
+
tenantId: credentials.tenantId,
|
|
71
|
+
endpointId: credentials.endpointId,
|
|
72
|
+
consumerId,
|
|
73
|
+
offset: 0,
|
|
74
|
+
leaseExpiresAt: new Date(),
|
|
75
|
+
leaseOffset: 0
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const now = new Date();
|
|
80
|
+
const leaseExpired = !consumer.leaseExpiresAt || new Date(consumer.leaseExpiresAt) <= now;
|
|
81
|
+
const fromOffset = toOffset(leaseExpired ? consumer.offset : consumer.leaseOffset);
|
|
82
|
+
if (leaseExpired) {
|
|
83
|
+
consumer.leaseOffset = toOffset(consumer.offset);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const attempts = await models.attempt.findAll({
|
|
87
|
+
where: {
|
|
88
|
+
tenantId: credentials.tenantId,
|
|
89
|
+
endpointId: credentials.endpointId,
|
|
90
|
+
status: { [Op.in]: ['pending', 'retrying', 'sending'] },
|
|
91
|
+
id: { [Op.gt]: fromOffset }
|
|
92
|
+
},
|
|
93
|
+
order: [['id', 'ASC']],
|
|
94
|
+
limit: Math.min(Number(batchSize) || 100, 1000)
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
const maxOffset = attempts.length ? toOffset(attempts[attempts.length - 1].id) : fromOffset;
|
|
98
|
+
consumer.leaseOffset = maxOffset;
|
|
99
|
+
consumer.leaseExpiresAt = new Date(Date.now() + LEASE_DURATION);
|
|
100
|
+
await consumer.save();
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
messages: attempts.map(attempt => ({
|
|
104
|
+
offset: toOffset(attempt.id),
|
|
105
|
+
attemptId: String(attempt.id),
|
|
106
|
+
webhookId: attempt.webhookId,
|
|
107
|
+
body: attempt.requestBody,
|
|
108
|
+
headers: attempt.requestHeaders,
|
|
109
|
+
retryCount: attempt.retryCount
|
|
110
|
+
})),
|
|
111
|
+
offset: toOffset(consumer.offset),
|
|
112
|
+
nextOffset: maxOffset
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
/** 提交 offset:确认消费成功 */
|
|
117
|
+
const commit = async ({ token, apiKey, consumerId, offset }) => {
|
|
118
|
+
const credentials = await models.pollingEndpoint.findOne({ where: { tokenHash: utils.hashToken(token), status: 'active' } });
|
|
119
|
+
if (!credentials || !safeEqual(credentials.apiKeyHash, utils.hashToken(apiKey || ''))) {
|
|
120
|
+
const error = new Error('Polling 凭证无效');
|
|
121
|
+
error.statusCode = 401;
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
const consumer = await models.pollingConsumer.findOne({
|
|
125
|
+
where: { tenantId: credentials.tenantId, endpointId: credentials.endpointId, consumerId }
|
|
126
|
+
});
|
|
127
|
+
if (!consumer) {
|
|
128
|
+
const error = new Error('consumer 不存在');
|
|
129
|
+
error.statusCode = 404;
|
|
130
|
+
throw error;
|
|
131
|
+
}
|
|
132
|
+
const previousOffset = toOffset(consumer.offset);
|
|
133
|
+
const target = minOffset(offset, consumer.leaseOffset);
|
|
134
|
+
if (compareOffset(target, previousOffset) > 0) {
|
|
135
|
+
// 必须用提交前的 previousOffset 过滤,否则 offset 已推进后查不到本批 attempt
|
|
136
|
+
const attempts = await models.attempt.findAll({
|
|
137
|
+
where: {
|
|
138
|
+
tenantId: credentials.tenantId,
|
|
139
|
+
endpointId: credentials.endpointId,
|
|
140
|
+
id: { [Op.gt]: previousOffset, [Op.lte]: target }
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
for (const attempt of attempts) {
|
|
144
|
+
attempt.status = 'success';
|
|
145
|
+
attempt.responseStatus = 200;
|
|
146
|
+
attempt.responseBody = 'acked by polling consumer';
|
|
147
|
+
attempt.endAt = new Date();
|
|
148
|
+
await attempt.save();
|
|
149
|
+
}
|
|
150
|
+
if (attempts[0]?.messageId) {
|
|
151
|
+
await services.delivery.finalizeMessage(credentials.tenantId, attempts[0].messageId);
|
|
152
|
+
}
|
|
153
|
+
consumer.offset = target;
|
|
154
|
+
await consumer.save();
|
|
155
|
+
}
|
|
156
|
+
consumer.leaseExpiresAt = new Date();
|
|
157
|
+
await consumer.save();
|
|
158
|
+
return { offset: toOffset(consumer.offset) };
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
fastify[options.name].services.polling = { createCredentials, consume, commit };
|
|
162
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { DEFAULT_PAYLOAD_RETENTION_DAYS } = require('../constants');
|
|
5
|
+
|
|
6
|
+
module.exports = fp(async (fastify, options) => {
|
|
7
|
+
const ctx = fastify[options.name].context;
|
|
8
|
+
const { models, Op } = ctx;
|
|
9
|
+
|
|
10
|
+
/** 清理超出保留期的 message payload 与过期记录 */
|
|
11
|
+
const cleanup = async () => {
|
|
12
|
+
const now = new Date();
|
|
13
|
+
const defaultCutoff = new Date(now.getTime() - (options.payloadRetentionDays || DEFAULT_PAYLOAD_RETENTION_DAYS) * 24 * 60 * 60 * 1000);
|
|
14
|
+
|
|
15
|
+
// 单条自定义保留期:逐条判断(自定义保留期的记录数量通常有限)
|
|
16
|
+
const customRecords = await models.message.findAll({
|
|
17
|
+
where: { payloadRetentionPeriod: { [Op.ne]: null }, payload: { [Op.ne]: null } },
|
|
18
|
+
attributes: ['id', 'createdAt', 'payloadRetentionPeriod']
|
|
19
|
+
});
|
|
20
|
+
let purged = 0;
|
|
21
|
+
for (const record of customRecords) {
|
|
22
|
+
const cutoff = new Date(now.getTime() - Number(record.payloadRetentionPeriod) * 24 * 60 * 60 * 1000);
|
|
23
|
+
if (new Date(record.createdAt) < cutoff) {
|
|
24
|
+
await models.message.update({ payload: null, rawBody: null }, { where: { id: record.id } });
|
|
25
|
+
purged++;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// 默认保留期
|
|
30
|
+
const [defaultPurged] = await models.message.update(
|
|
31
|
+
{ payload: null, rawBody: null },
|
|
32
|
+
{
|
|
33
|
+
where: {
|
|
34
|
+
payloadRetentionPeriod: { [Op.or]: [{ [Op.is]: null }, DEFAULT_PAYLOAD_RETENTION_DAYS] },
|
|
35
|
+
createdAt: { [Op.lt]: defaultCutoff },
|
|
36
|
+
payload: { [Op.ne]: null }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
// 过期幂等记录 / inbox / portal 会话
|
|
42
|
+
await models.idempotency.destroy({ where: { expiresAt: { [Op.lt]: now } } });
|
|
43
|
+
await models.appPortalSession.destroy({ where: { expiresAt: { [Op.lt]: now } } });
|
|
44
|
+
|
|
45
|
+
return { purged: purged + defaultPurged };
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
let timer = null;
|
|
49
|
+
const start = () => {
|
|
50
|
+
if (timer || !options.retentionInterval) return;
|
|
51
|
+
timer = setInterval(() => {
|
|
52
|
+
cleanup().catch(error => fastify.log?.error?.({ err: error }, 'retention cleanup failed'));
|
|
53
|
+
}, options.retentionInterval);
|
|
54
|
+
timer.unref?.();
|
|
55
|
+
};
|
|
56
|
+
const stop = () => {
|
|
57
|
+
if (timer) {
|
|
58
|
+
clearInterval(timer);
|
|
59
|
+
timer = null;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
fastify.addHook('onReady', start);
|
|
63
|
+
fastify.addHook('onClose', stop);
|
|
64
|
+
|
|
65
|
+
fastify[options.name].services.retention = { cleanup, start, stop };
|
|
66
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
|
|
5
|
+
module.exports = fp(async (fastify, options) => {
|
|
6
|
+
const ctx = fastify[options.name].context;
|
|
7
|
+
const { services } = ctx;
|
|
8
|
+
|
|
9
|
+
let timer = null;
|
|
10
|
+
let running = false;
|
|
11
|
+
|
|
12
|
+
/** 单次 tick,串行执行到期任务,避免并发重复投递 */
|
|
13
|
+
const tick = async () => {
|
|
14
|
+
if (running) {
|
|
15
|
+
return { skipped: true, reason: 'previous tick still running' };
|
|
16
|
+
}
|
|
17
|
+
running = true;
|
|
18
|
+
try {
|
|
19
|
+
return await services.delivery.runDue(options.schedulerBatchSize || 100);
|
|
20
|
+
} finally {
|
|
21
|
+
running = false;
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const start = () => {
|
|
26
|
+
if (timer || !options.schedulerInterval) {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
timer = setInterval(() => {
|
|
30
|
+
tick().catch(error => fastify.log?.error?.({ err: error }, 'webhook scheduler tick failed'));
|
|
31
|
+
}, options.schedulerInterval);
|
|
32
|
+
timer.unref?.();
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const stop = () => {
|
|
36
|
+
if (timer) {
|
|
37
|
+
clearInterval(timer);
|
|
38
|
+
timer = null;
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
fastify.addHook('onReady', () => {
|
|
43
|
+
start();
|
|
44
|
+
});
|
|
45
|
+
fastify.addHook('onClose', () => {
|
|
46
|
+
stop();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
fastify[options.name].services.scheduler = { tick, start, stop };
|
|
50
|
+
});
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { adapters, formatEvents } = require('../sinks');
|
|
5
|
+
|
|
6
|
+
module.exports = fp(async (fastify, options) => {
|
|
7
|
+
const ctx = fastify[options.name].context;
|
|
8
|
+
const { models, services } = ctx;
|
|
9
|
+
|
|
10
|
+
const deliver = async (sink, events) => {
|
|
11
|
+
const adapter = adapters[sink.type];
|
|
12
|
+
if (!adapter) {
|
|
13
|
+
return { success: false, error: `不支持的 Sink 类型: ${sink.type}` };
|
|
14
|
+
}
|
|
15
|
+
const config = sink.config || {};
|
|
16
|
+
let transformedEvents = events;
|
|
17
|
+
if (sink.transformation?.code && services.transform) {
|
|
18
|
+
try {
|
|
19
|
+
const result = await services.transform.run(sink.transformation.code, {
|
|
20
|
+
config: { format: config.format || 'jsonl', key: config.key },
|
|
21
|
+
data: events.map(item => ({ eventType: item.eventType, payload: item.payload })),
|
|
22
|
+
events: events.map(item => ({ eventType: item.eventType, payload: item.payload }))
|
|
23
|
+
}, sink.transformation.variables || {});
|
|
24
|
+
if (result?.cancel) {
|
|
25
|
+
return { success: true, canceled: true };
|
|
26
|
+
}
|
|
27
|
+
if (Array.isArray(result?.data)) {
|
|
28
|
+
transformedEvents = result.data.map(item => ({ eventType: item.eventType, payload: item.payload }));
|
|
29
|
+
}
|
|
30
|
+
} catch (error) {
|
|
31
|
+
return { success: false, error: `Sink transformation 失败: ${error.message}` };
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const context = {
|
|
36
|
+
fetch: async (url, init = {}) => {
|
|
37
|
+
const response = await ctx.utils.sendHttp(
|
|
38
|
+
{
|
|
39
|
+
method: init.method || 'POST',
|
|
40
|
+
url,
|
|
41
|
+
headers: init.headers || {},
|
|
42
|
+
body: init.body
|
|
43
|
+
},
|
|
44
|
+
{ httpClient: options.httpClient, allowPrivateUrl: options.allowPrivateUrl }
|
|
45
|
+
);
|
|
46
|
+
return {
|
|
47
|
+
ok: response.status >= 200 && response.status < 300,
|
|
48
|
+
status: response.status,
|
|
49
|
+
headers: response.headers,
|
|
50
|
+
text: async () => response.body,
|
|
51
|
+
json: async () => JSON.parse(response.body || '{}')
|
|
52
|
+
};
|
|
53
|
+
},
|
|
54
|
+
log: fastify.log
|
|
55
|
+
};
|
|
56
|
+
try {
|
|
57
|
+
const result = await adapter(context, transformedEvents, config);
|
|
58
|
+
sink.lastProcessedAt = new Date();
|
|
59
|
+
await sink.save();
|
|
60
|
+
return result;
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return { success: false, error: error.message };
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
fastify[options.name].services.sink = { deliver, adapters, formatEvents };
|
|
67
|
+
});
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { SINK_TYPES } = require('../constants');
|
|
5
|
+
|
|
6
|
+
module.exports = fp(async (fastify, options) => {
|
|
7
|
+
const ctx = fastify[options.name].context;
|
|
8
|
+
const { models, utils, pageParams, tenantWhere, services, Op } = ctx;
|
|
9
|
+
|
|
10
|
+
const createStream = async (authenticatePayload, data) => {
|
|
11
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
12
|
+
if (!data.name) {
|
|
13
|
+
throw new Error('Stream 名称不能为空');
|
|
14
|
+
}
|
|
15
|
+
if (data.uid) {
|
|
16
|
+
const exists = await models.stream.findOne({ where: tenantWhere(authenticatePayload, { uid: data.uid }) });
|
|
17
|
+
if (exists) {
|
|
18
|
+
return exists;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return models.stream.create({ tenantId, name: data.name, uid: data.uid, description: data.description, status: 'active' });
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const saveStream = async (authenticatePayload, data) => {
|
|
25
|
+
const record = await models.stream.findOne({ where: tenantWhere(authenticatePayload, { id: data.id }) });
|
|
26
|
+
if (!record) {
|
|
27
|
+
throw new Error('Stream 不存在');
|
|
28
|
+
}
|
|
29
|
+
if (data.name !== undefined) record.name = data.name;
|
|
30
|
+
if (data.description !== undefined) record.description = data.description;
|
|
31
|
+
if (data.status !== undefined) record.status = data.status;
|
|
32
|
+
await record.save();
|
|
33
|
+
return record;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
const removeStream = async (authenticatePayload, { id }) => {
|
|
37
|
+
await models.sink.destroy({ where: tenantWhere(authenticatePayload, { streamId: id }) });
|
|
38
|
+
await models.streamEvent.destroy({ where: tenantWhere(authenticatePayload, { streamId: id }) });
|
|
39
|
+
await models.stream.destroy({ where: tenantWhere(authenticatePayload, { id }) });
|
|
40
|
+
return {};
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const listStreams = async (authenticatePayload, params = {}) => {
|
|
44
|
+
const { offset, limit } = pageParams(params);
|
|
45
|
+
const { count, rows } = await models.stream.findAndCountAll({
|
|
46
|
+
where: tenantWhere(authenticatePayload), offset, limit, order: [['createdAt', 'DESC']]
|
|
47
|
+
});
|
|
48
|
+
return { pageData: rows, totalCount: count };
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const createSink = async (authenticatePayload, streamId, data) => {
|
|
52
|
+
if (!SINK_TYPES.includes(data.type)) {
|
|
53
|
+
throw new Error(`不支持的 Sink 类型: ${data.type}`);
|
|
54
|
+
}
|
|
55
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
56
|
+
return models.sink.create({
|
|
57
|
+
streamId,
|
|
58
|
+
tenantId,
|
|
59
|
+
type: data.type,
|
|
60
|
+
uid: data.uid,
|
|
61
|
+
config: data.config || {},
|
|
62
|
+
batchSize: data.batchSize || 100,
|
|
63
|
+
maxWaitSecs: data.maxWaitSecs || 5,
|
|
64
|
+
eventTypes: data.eventTypes || [],
|
|
65
|
+
metadata: data.metadata || {},
|
|
66
|
+
transformation: data.transformation || null,
|
|
67
|
+
status: 'active'
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const saveSink = async (authenticatePayload, data) => {
|
|
72
|
+
const record = await models.sink.findOne({ where: tenantWhere(authenticatePayload, { id: data.id }) });
|
|
73
|
+
if (!record) {
|
|
74
|
+
throw new Error('Sink 不存在');
|
|
75
|
+
}
|
|
76
|
+
['config', 'batchSize', 'maxWaitSecs', 'eventTypes', 'metadata', 'transformation', 'status'].forEach(key => {
|
|
77
|
+
if (data[key] !== undefined) {
|
|
78
|
+
record[key] = data[key];
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
await record.save();
|
|
82
|
+
return record;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const removeSink = async (authenticatePayload, { id }) => {
|
|
86
|
+
await models.sink.destroy({ where: tenantWhere(authenticatePayload, { id }) });
|
|
87
|
+
return {};
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const listSinks = async (authenticatePayload, { streamId }) => {
|
|
91
|
+
const where = tenantWhere(authenticatePayload);
|
|
92
|
+
if (streamId) where.streamId = streamId;
|
|
93
|
+
return models.sink.findAll({ where, order: [['createdAt', 'DESC']] });
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/** 写入批量事件到 Stream */
|
|
97
|
+
const publishEvents = async (authenticatePayload, streamId, events) => {
|
|
98
|
+
if (!Array.isArray(events) || !events.length) {
|
|
99
|
+
throw new Error('events 不能为空');
|
|
100
|
+
}
|
|
101
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
102
|
+
const records = await models.streamEvent.bulkCreate(
|
|
103
|
+
events.map(event => ({
|
|
104
|
+
streamId,
|
|
105
|
+
tenantId,
|
|
106
|
+
eventType: event.eventType || event.type,
|
|
107
|
+
payload: event.payload,
|
|
108
|
+
consumed: false,
|
|
109
|
+
createdAt: new Date()
|
|
110
|
+
}))
|
|
111
|
+
);
|
|
112
|
+
// 按 sink 配置批处理
|
|
113
|
+
const sinks = await models.sink.findAll({ where: { tenantId, streamId, status: 'active' } });
|
|
114
|
+
const results = [];
|
|
115
|
+
for (const sink of sinks) {
|
|
116
|
+
const filtered = records.filter(record => sink.eventTypes.length === 0 || sink.eventTypes.includes(record.eventType));
|
|
117
|
+
if (filtered.length) {
|
|
118
|
+
results.push(await services.sink.deliver(sink, filtered));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (results.every(item => item.success)) {
|
|
122
|
+
await models.streamEvent.update({ consumed: true }, { where: { id: { [Op.in]: records.map(item => item.id) } } });
|
|
123
|
+
}
|
|
124
|
+
return { published: records.length, sinks: results };
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
fastify[options.name].services.stream = {
|
|
128
|
+
createStream,
|
|
129
|
+
saveStream,
|
|
130
|
+
removeStream,
|
|
131
|
+
listStreams,
|
|
132
|
+
createSink,
|
|
133
|
+
saveSink,
|
|
134
|
+
removeSink,
|
|
135
|
+
listSinks,
|
|
136
|
+
publishEvents
|
|
137
|
+
};
|
|
138
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 平滑限流:以滑动窗口统计每个应用/端点最近 1 秒的投递数。
|
|
7
|
+
* rate <= 0 表示不限流。返回需要等待的毫秒数(0 表示可直接投递)。
|
|
8
|
+
*/
|
|
9
|
+
module.exports = fp(async (fastify, options) => {
|
|
10
|
+
const windows = new Map(); // key -> [{ ts, count }]
|
|
11
|
+
|
|
12
|
+
const prune = (entries, now) => entries.filter(item => now - item.ts < 1000);
|
|
13
|
+
|
|
14
|
+
const consume = (key, rate) => {
|
|
15
|
+
if (!rate || rate <= 0) {
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
const now = Date.now();
|
|
19
|
+
let entries = prune(windows.get(key) || [], now);
|
|
20
|
+
const current = entries.reduce((sum, item) => sum + item.count, 0);
|
|
21
|
+
if (current >= rate) {
|
|
22
|
+
// 需要等待到窗口中最早记录滑出
|
|
23
|
+
const oldest = entries.length ? entries[0].ts : now;
|
|
24
|
+
return Math.max(1, 1000 - (now - oldest));
|
|
25
|
+
}
|
|
26
|
+
entries.push({ ts: now, count: 1 });
|
|
27
|
+
windows.set(key, entries);
|
|
28
|
+
return 0;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** 计算端点的有效限流:端点级覆盖应用级 */
|
|
32
|
+
const effectiveRate = async (endpoint) => {
|
|
33
|
+
if (endpoint.throttleRate != null) {
|
|
34
|
+
return endpoint.throttleRate;
|
|
35
|
+
}
|
|
36
|
+
const application = await fastify[options.name].models.application.findOne({
|
|
37
|
+
where: { tenantId: endpoint.tenantId, id: endpoint.applicationId }
|
|
38
|
+
});
|
|
39
|
+
return application?.throttleRate || 0;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
/** 等待直到可以投递(异步节流) */
|
|
43
|
+
const waitForSlot = async (endpoint, application) => {
|
|
44
|
+
const rate = endpoint.throttleRate != null ? endpoint.throttleRate : application?.throttleRate;
|
|
45
|
+
if (!rate || rate <= 0) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
let wait = consume(`endpoint:${endpoint.id}`, rate);
|
|
49
|
+
if (wait > 0) {
|
|
50
|
+
await new Promise(resolve => setTimeout(resolve, Math.min(wait, 5000)));
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const reset = key => {
|
|
55
|
+
if (key) {
|
|
56
|
+
windows.delete(key);
|
|
57
|
+
} else {
|
|
58
|
+
windows.clear();
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
fastify[options.name].services.throttle = { consume, effectiveRate, waitForSlot, reset };
|
|
63
|
+
});
|