@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
package/README.md CHANGED
@@ -1,11 +1,8 @@
1
-
2
1
  # fastify-webhook
3
2
 
4
-
5
3
  ### 描述
6
4
 
7
- 实现一个webhook功能.
8
-
5
+ Fastify Webhook 引擎:应用 / 端点 / 消息 / 投递 / 重试 / Ingest / Stream / Polling / Portal / Play 调试器的全量实现,签名对齐 Standard Webhooks。
9
6
 
10
7
  ### 安装
11
8
 
@@ -13,15 +10,28 @@
13
10
  npm i --save @kne/fastify-webhook
14
11
  ```
15
12
 
16
- ### 示例
13
+ ### 概述
17
14
 
18
- #### 示例代码
15
+ 详见 `doc/summary.md`。更完整的 API 说明见 `doc/api.md`。可用 `npm run build:md` 将文档生成到本 README。
19
16
 
17
+ ### 基础配置
20
18
 
19
+ ```javascript
20
+ const fastify = require('fastify')();
21
21
 
22
- ### API
22
+ fastify.register(require('@kne/fastify-sequelize'), {
23
+ db: { dialect: 'sqlite', storage: ':memory:' }
24
+ });
25
+
26
+ fastify.register(require('@kne/fastify-webhook'), {
27
+ prefix: '/api/v1/webhook',
28
+ dbTableNamePrefix: 't_webhook_',
29
+ getTenantId: request => request.tenantId || '',
30
+ // 生产默认 false;本地/测试可传 true 做 sync alter
31
+ autoUpgrade: false
32
+ });
33
+ ```
23
34
 
24
- | 属性名 | 说明 | 类型 | 默认值 |
25
- |-----|----|----|-----|
26
- | | | | |
35
+ ### 版本说明
27
36
 
37
+ `1.0.0` 相对旧版 `0.1.3`(client/invocation 薄模型)为**破坏性升级**,数据模型与 API 面全面替换,请按新文档接入。
package/index.js CHANGED
@@ -1,51 +1,60 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const path = require('node:path');
3
3
 
4
- module.exports = fp(async (fastify, options) => {
5
- options = Object.assign(
6
- {},
7
- {
8
- prefix: '/api/webhook',
9
- dbTableNamePrefix: 't_',
10
- name: 'webhook',
11
- hooks: {},
12
- rawBodyField: 'rawBody',
13
- getUserAuthenticate: () => {
14
- if (!fastify.account) {
15
- throw new Error('fastify-account plugin must be registered before fastify-trtc,or set options.getUserAuthenticate');
16
- }
17
- return fastify.account.authenticate.user;
4
+ module.exports = fp(
5
+ async (fastify, rawOptions) => {
6
+ const options = Object.assign(
7
+ {},
8
+ {
9
+ name: 'webhook',
10
+ dbTableNamePrefix: 't_webhook_',
11
+ prefix: '/api/v1/webhook',
12
+ publicPrefix: '/api/v1/webhook',
13
+ region: 'default',
14
+ enableTransformations: true,
15
+ transformTimeout: 1000,
16
+ schedulerInterval: 1000,
17
+ schedulerBatchSize: 100,
18
+ autoDisable: true,
19
+ allowPrivateUrl: false,
20
+ timestampTolerance: 5 * 60 * 1000,
21
+ // 生产默认关闭 alter sync,避免误改现网表结构;本地/测试显式传 true
22
+ autoUpgrade: false,
23
+ getTenantId: request => request.tenantId || request.tenantUserInfo?.tenantId || request.userInfo?.tenantId || '',
24
+ getAuthenticate: () => [],
25
+ onInbound: null
18
26
  },
19
- getAdminAuthenticate: () => {
20
- if (!fastify.account) {
21
- throw new Error('fastify-account plugin must be registered before fastify-trtc,or set options.getAdminAuthenticate');
22
- }
23
- return fastify.account.authenticate.admin;
24
- },
25
- getUserModel: () => {
26
- if (!fastify.account) {
27
- throw new Error('fastify-account plugin must be registered before fastify-trtc,or set options.getUserModel');
28
- }
29
- return fastify.account.models.user;
30
- }
31
- },
32
- options
33
- );
27
+ rawOptions
28
+ );
29
+
30
+ if (typeof rawOptions.getTenantId !== 'function' && rawOptions.tenantId != null) {
31
+ // 允许通过 tenantId 常量配置固定租户
32
+ options.getTenantId = () => String(rawOptions.tenantId);
33
+ }
34
+
35
+ if (options.autoUpgrade) {
36
+ fastify.addHook('onReady', async () => {
37
+ await fastify.sequelize.instance.sync({ alter: true });
38
+ });
39
+ }
34
40
 
35
- fastify.register(require('@kne/fastify-namespace'), {
36
- options,
37
- name: options.name,
38
- modules: [
39
- ['controllers', path.resolve(__dirname, './libs/controllers')],
40
- [
41
- 'models',
42
- await fastify.sequelize.addModels(path.resolve(__dirname, './libs/models'), {
43
- prefix: options.dbTableNamePrefix,
44
- modelPrefix: options.name,
45
- getUserModel: options.getUserModel
46
- })
47
- ],
48
- ['services', path.resolve(__dirname, './libs/services')]
49
- ]
50
- });
51
- });
41
+ // helpers 先注册:为 services 提供 context
42
+ fastify.register(require('@kne/fastify-namespace'), {
43
+ name: options.name,
44
+ options,
45
+ modules: [
46
+ [
47
+ 'models',
48
+ await fastify.sequelize.addModels(path.resolve(__dirname, './libs/models'), {
49
+ prefix: options.dbTableNamePrefix
50
+ })
51
+ ],
52
+ ['utils', path.resolve(__dirname, './libs/utils/index.js')],
53
+ ['context', path.resolve(__dirname, './libs/helpers/context.js')],
54
+ ['services', path.resolve(__dirname, './libs/services')],
55
+ ['controllers', path.resolve(__dirname, './libs/controllers')]
56
+ ]
57
+ });
58
+ },
59
+ { name: 'fastify-webhook' }
60
+ );
@@ -0,0 +1,81 @@
1
+ 'use strict';
2
+
3
+ // 重试计划:每次失败后开始计时(毫秒)。索引 0 表示首次失败后的立即重试。
4
+ const RETRY_SCHEDULE = [0, 5 * 1000, 5 * 60 * 1000, 30 * 60 * 1000, 2 * 60 * 60 * 1000, 5 * 60 * 60 * 1000, 10 * 60 * 60 * 1000, 10 * 60 * 60 * 1000];
5
+
6
+ const MAX_RETRY_AFTER = 7 * 24 * 60 * 60 * 1000; // 7 天
7
+ const DELIVERY_TIMEOUT = 30 * 1000; // 30 秒
8
+ const DEFAULT_PAYLOAD_RETENTION_DAYS = 90;
9
+ const TIMESTAMP_TOLERANCE = 5 * 60 * 1000; // 5 分钟
10
+ const SECRET_PREFIX = 'whsec_';
11
+ const SIGNATURE_HEADER = 'webhook-signature';
12
+ const ID_HEADER = 'webhook-id';
13
+ const TIMESTAMP_HEADER = 'webhook-timestamp';
14
+
15
+ const MESSAGE_STATUS = ['pending', 'sending', 'success', 'failed', 'aborted'];
16
+ const ATTEMPT_STATUS = ['pending', 'sending', 'success', 'failed', 'retrying'];
17
+ const ENDPOINT_STATUS = ['active', 'disabled', 'paused'];
18
+ const ENDPOINT_KIND = ['http', 'fifo', 'polling', 'sink'];
19
+ const ENDPOINT_DIRECTION = ['inbound', 'outbound'];
20
+
21
+ const OPERATIONAL_EVENTS = [
22
+ 'endpoint.disabled',
23
+ 'endpoint.enabled',
24
+ 'message.attempt.exhausted',
25
+ 'message.created',
26
+ 'message.delivered',
27
+ 'application.created',
28
+ 'application.removed'
29
+ ];
30
+
31
+ const RETENTION_POLICY = ['keep', 'delete-on-delivery', 'delete-on-expiry'];
32
+
33
+ const SINK_TYPES = [
34
+ 'amazonS3',
35
+ 'amazonSQS',
36
+ 'snowflake',
37
+ 'bigQuery',
38
+ 'rabbitMQ',
39
+ 'datadog',
40
+ 'clickHouse',
41
+ 'eventBridge',
42
+ 'azureBlob',
43
+ 'googleCloudStorage'
44
+ ];
45
+
46
+ const INGEST_HEADERS = {
47
+ trailingPath: 'x-webhook-ingest-trailing-path-segments',
48
+ query: 'x-webhook-ingest-query'
49
+ };
50
+
51
+ const CATALOG_EXTENSIONS = {
52
+ featureFlags: 'x-webhook-feature-flags',
53
+ groupName: 'x-webhook-group-name'
54
+ };
55
+
56
+ const SIGNATURE_SCHEME = 'v1';
57
+ const GLOBAL_TENANT_ID = '';
58
+
59
+ module.exports = {
60
+ RETRY_SCHEDULE,
61
+ MAX_RETRY_AFTER,
62
+ DELIVERY_TIMEOUT,
63
+ DEFAULT_PAYLOAD_RETENTION_DAYS,
64
+ TIMESTAMP_TOLERANCE,
65
+ SECRET_PREFIX,
66
+ SIGNATURE_HEADER,
67
+ ID_HEADER,
68
+ TIMESTAMP_HEADER,
69
+ MESSAGE_STATUS,
70
+ ATTEMPT_STATUS,
71
+ ENDPOINT_STATUS,
72
+ ENDPOINT_KIND,
73
+ ENDPOINT_DIRECTION,
74
+ OPERATIONAL_EVENTS,
75
+ RETENTION_POLICY,
76
+ SINK_TYPES,
77
+ INGEST_HEADERS,
78
+ CATALOG_EXTENSIONS,
79
+ SIGNATURE_SCHEME,
80
+ GLOBAL_TENANT_ID
81
+ };
@@ -0,0 +1,16 @@
1
+ 'use strict';
2
+
3
+ /** 从 request 构造传给 service 的认证上下文,tenantId 只由 getTenantId 注入 */
4
+ const auth = (options, request) => {
5
+ const tenantId = options.getTenantId ? options.getTenantId(request) : request.tenantId;
6
+ return {
7
+ tenantId,
8
+ ...(request.tenantUserInfo || {}),
9
+ ...(request.userInfo || {}),
10
+ request
11
+ };
12
+ };
13
+
14
+ const getAuthenticate = (options, scope = 'write') => (options.getAuthenticate ? options.getAuthenticate(scope) : []);
15
+
16
+ module.exports = { auth, getAuthenticate };
@@ -0,0 +1,73 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const { any, success, empty, application, applicationList } = require('../schema/response');
5
+ const { auth: buildAuth, getAuthenticate: buildAuthenticate } = require('./_helper');
6
+
7
+ const TAG = 'Webhook-应用管理';
8
+
9
+ module.exports = fp(async (fastify, options) => {
10
+ const { services } = fastify[options.name];
11
+ const auth = request => buildAuth(options, request);
12
+ const getAuthenticate = () => buildAuthenticate(options, 'write');
13
+ const getReadAuthenticate = () => buildAuthenticate(options, 'read');
14
+
15
+ fastify.post(`${options.prefix}/application/create`, {
16
+ onRequest: getAuthenticate(),
17
+ schema: {
18
+ tags: [TAG],
19
+ summary: '创建应用',
20
+ description: '创建一个 Webhook 消费者应用,可用 uid 直接映射业务客户 ID',
21
+ body: {
22
+ type: 'object',
23
+ additionalProperties: true,
24
+ properties: {
25
+ name: { type: 'string', description: '应用名称' },
26
+ uid: { type: 'string', description: '外部消费者 ID' },
27
+ description: { type: 'string', description: '描述' },
28
+ throttleRate: { type: 'number', description: '应用级限流 messages/sec' },
29
+ region: { type: 'string', description: '数据驻留区域' },
30
+ metadata: { type: 'object', description: '扩展元数据' }
31
+ },
32
+ required: ['name']
33
+ },
34
+ response: success('创建成功', application)
35
+ }
36
+ }, async request => services.application.create(auth(request), request.body));
37
+
38
+ fastify.post(`${options.prefix}/application/save`, {
39
+ onRequest: getAuthenticate(),
40
+ schema: {
41
+ tags: [TAG], summary: '保存应用', description: '更新应用配置,白名单字段之外的属性不会被修改',
42
+ body: { type: 'object', additionalProperties: true, properties: { id: any('应用 ID'), name: { type: 'string' }, description: { type: 'string' }, throttleRate: { type: 'number' }, status: { type: 'string' }, region: { type: 'string' }, metadata: { type: 'object' } }, required: ['id'] },
43
+ response: success('保存成功', application)
44
+ }
45
+ }, async request => services.application.save(auth(request), request.body));
46
+
47
+ fastify.post(`${options.prefix}/application/remove`, {
48
+ onRequest: getAuthenticate(),
49
+ schema: {
50
+ tags: [TAG], summary: '删除应用', description: '删除应用及其下所有端点',
51
+ body: { type: 'object', properties: { id: any('应用 ID') }, required: ['id'] },
52
+ response: empty()
53
+ }
54
+ }, async request => services.application.remove(auth(request), request.body));
55
+
56
+ fastify.get(`${options.prefix}/application/list`, {
57
+ onRequest: getReadAuthenticate(),
58
+ schema: {
59
+ tags: [TAG], summary: '应用列表', description: '分页查询应用,支持名称模糊搜索与状态过滤',
60
+ querystring: { type: 'object', properties: { name: { type: 'string', description: '名称关键字' }, uid: { type: 'string', description: '外部 ID' }, status: { type: 'string', description: '状态' }, currentPage: { type: 'number', description: '页码' }, perPage: { type: 'number', description: '每页条数' } } },
61
+ response: success('查询成功', applicationList)
62
+ }
63
+ }, async request => services.application.list(auth(request), request.query));
64
+
65
+ fastify.get(`${options.prefix}/application/detail`, {
66
+ onRequest: getReadAuthenticate(),
67
+ schema: {
68
+ tags: [TAG], summary: '应用详情', description: '按 id 或 uid 查询单个应用',
69
+ querystring: { type: 'object', properties: { id: any('应用 ID'), uid: { type: 'string', description: '外部 ID' } } },
70
+ response: success('查询成功', application)
71
+ }
72
+ }, async request => services.application.detail(auth(request), request.query));
73
+ });
@@ -0,0 +1,49 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const { any, str, success, attempt, attemptList } = require('../schema/response');
5
+ const { auth: buildAuth, getAuthenticate: buildAuthenticate } = require('./_helper');
6
+
7
+ const TAG = 'Webhook-投递记录';
8
+
9
+ module.exports = fp(async (fastify, options) => {
10
+ const { services } = fastify[options.name];
11
+ const auth = request => buildAuth(options, request);
12
+ const w = buildAuthenticate(options, 'write');
13
+ const r = buildAuthenticate(options, 'read');
14
+
15
+ fastify.get(`${options.prefix}/attempt/list`, {
16
+ onRequest: r,
17
+ schema: { tags: [TAG], summary: '投递记录列表', description: '分页查询投递尝试记录',
18
+ querystring: { type: 'object', properties: { messageId: any('消息 ID'), endpointId: any('端点 ID'), status: str('状态'), retryCount: { type: 'number' }, startTime: str('起始时间'), endTime: str('结束时间'), currentPage: { type: 'number' }, perPage: { type: 'number' } } },
19
+ response: success('查询成功', attemptList) }
20
+ }, async request => services.attempt.list(auth(request), request.query));
21
+
22
+ fastify.get(`${options.prefix}/attempt/detail`, {
23
+ onRequest: r,
24
+ schema: { tags: [TAG], summary: '投递记录详情', description: '按 ID 查询单次投递记录',
25
+ querystring: { type: 'object', properties: { id: any('记录 ID') }, required: ['id'] },
26
+ response: success('查询成功', attempt) }
27
+ }, async request => services.attempt.detail(auth(request), request.query));
28
+
29
+ fastify.post(`${options.prefix}/attempt/resend`, {
30
+ onRequest: w,
31
+ schema: { tags: [TAG], summary: '单条重放', description: '重放一条投递记录,沿用原 webhook-id',
32
+ body: { type: 'object', properties: { id: any('记录 ID') }, required: ['id'] },
33
+ response: success('重放成功', { type: 'object', additionalProperties: true }) }
34
+ }, async request => services.attempt.resend(auth(request), request.body));
35
+
36
+ fastify.post(`${options.prefix}/attempt/recover-failed`, {
37
+ onRequest: w,
38
+ schema: { tags: [TAG], summary: '批量恢复失败', description: '按时间与应用恢复所有失败消息',
39
+ body: { type: 'object', properties: { startTime: str('起始时间'), applicationId: any('应用 ID') } },
40
+ response: success('恢复成功', { type: 'object', additionalProperties: true }) }
41
+ }, async request => services.attempt.recoverFailed(auth(request), request.body));
42
+
43
+ fastify.post(`${options.prefix}/attempt/replay-missing`, {
44
+ onRequest: w,
45
+ schema: { tags: [TAG], summary: '补发未投递消息', description: '补发从未投递到任何端点的消息',
46
+ body: { type: 'object', properties: { startTime: str('起始时间'), applicationId: any('应用 ID') } },
47
+ response: success('补发成功', { type: 'object', additionalProperties: true }) }
48
+ }, async request => services.attempt.replayMissing(auth(request), request.body));
49
+ });
@@ -0,0 +1,40 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const { any, str, success, empty } = require('../schema/response');
5
+ const { auth: buildAuth, getAuthenticate: buildAuthenticate } = require('./_helper');
6
+
7
+ const TAG = 'Webhook-自定义域名';
8
+
9
+ module.exports = fp(async (fastify, options) => {
10
+ const { services } = fastify[options.name];
11
+ const auth = request => buildAuth(options, request);
12
+ const w = buildAuthenticate(options, 'write');
13
+ const r = buildAuthenticate(options, 'read');
14
+
15
+ fastify.post(`${options.prefix}/custom-domain/create`, {
16
+ onRequest: w,
17
+ schema: { tags: [TAG], summary: '创建自定义域名', description: '为 ingest / portal / catalog / polling / mcp 服务配置自定义域名',
18
+ body: { type: 'object', properties: { domain: str('域名'), service: { type: 'string', enum: ['ingest', 'portal', 'catalog', 'polling', 'mcp'] }, region: str('区域') }, required: ['domain', 'service'] },
19
+ response: success('创建成功', { type: 'object', additionalProperties: true }) }
20
+ }, async request => services.customDomain.create(auth(request), request.body));
21
+
22
+ fastify.post(`${options.prefix}/custom-domain/verify`, {
23
+ onRequest: w,
24
+ schema: { tags: [TAG], summary: '验证自定义域名', description: '验证 CNAME 是否指向目标地址,验证通过后签发 TLS 证书',
25
+ body: { type: 'object', properties: { id: any('ID') }, required: ['id'] },
26
+ response: success('验证完成', { type: 'object', additionalProperties: true }) }
27
+ }, async request => services.customDomain.verify(auth(request), request.body));
28
+
29
+ fastify.get(`${options.prefix}/custom-domain/list`, {
30
+ onRequest: r,
31
+ schema: { tags: [TAG], summary: '自定义域名列表', description: '分页查询自定义域名',
32
+ querystring: { type: 'object', properties: { currentPage: { type: 'number' }, perPage: { type: 'number' } } } }
33
+ }, async request => services.customDomain.list(auth(request), request.query));
34
+
35
+ fastify.post(`${options.prefix}/custom-domain/remove`, {
36
+ onRequest: w,
37
+ schema: { tags: [TAG], summary: '删除自定义域名', description: '删除域名配置',
38
+ body: { type: 'object', properties: { id: any('ID') }, required: ['id'] }, response: empty() }
39
+ }, async request => services.customDomain.remove(auth(request), request.body));
40
+ });
@@ -0,0 +1,90 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const { any, str, success, empty, endpoint, endpointList } = require('../schema/response');
5
+ const { auth: buildAuth, getAuthenticate: buildAuthenticate } = require('./_helper');
6
+
7
+ const TAG = 'Webhook-端点管理';
8
+
9
+ module.exports = fp(async (fastify, options) => {
10
+ const { services } = fastify[options.name];
11
+ const auth = request => buildAuth(options, request);
12
+ const w = buildAuthenticate(options, 'write');
13
+ const r = buildAuthenticate(options, 'read');
14
+
15
+ const bodyProps = {
16
+ applicationId: any('应用 ID'),
17
+ uid: str('外部端点 ID'),
18
+ name: str('端点名称'),
19
+ url: str('接收 URL'),
20
+ direction: str('方向:inbound / outbound'),
21
+ kind: str('形态:http / fifo / polling / sink'),
22
+ eventTypes: { type: 'array', items: { type: 'string' }, description: '订阅事件类型' },
23
+ channels: { type: 'array', items: { type: 'string' }, description: '订阅 channels' },
24
+ headers: { type: 'object', description: '自定义请求头' },
25
+ throttleRate: { type: 'number', description: '端点级限流' },
26
+ rate: { type: 'number', description: 'FIFO 批量大小' },
27
+ expireAt: str('过期时间'),
28
+ options: { type: 'object', description: '扩展配置' },
29
+ description: str('描述'),
30
+ metadata: { type: 'object', description: '扩展元数据' }
31
+ };
32
+
33
+ fastify.post(`${options.prefix}/endpoint/create`, {
34
+ onRequest: w,
35
+ schema: { tags: [TAG], summary: '创建端点', description: '创建接收端点,自动生成签名密钥;密钥仅创建时明文返回',
36
+ body: { type: 'object', additionalProperties: true, properties: bodyProps, required: ['applicationId'] },
37
+ response: success('创建成功', endpoint) }
38
+ }, async request => services.endpoint.create(auth(request), request.body));
39
+
40
+ fastify.post(`${options.prefix}/endpoint/save`, {
41
+ onRequest: w,
42
+ schema: { tags: [TAG], summary: '保存端点', description: '更新端点配置,白名单之外的字段不修改',
43
+ body: { type: 'object', additionalProperties: true, properties: { id: any('端点 ID'), ...bodyProps }, required: ['id'] },
44
+ response: success('保存成功', endpoint) }
45
+ }, async request => services.endpoint.save(auth(request), request.body));
46
+
47
+ fastify.post(`${options.prefix}/endpoint/remove`, {
48
+ onRequest: w,
49
+ schema: { tags: [TAG], summary: '删除端点', description: '删除端点及其变换脚本与 Polling 凭证',
50
+ body: { type: 'object', properties: { id: any('端点 ID') }, required: ['id'] }, response: empty() }
51
+ }, async request => services.endpoint.remove(auth(request), request.body));
52
+
53
+ fastify.post(`${options.prefix}/endpoint/set-status`, {
54
+ onRequest: w,
55
+ schema: { tags: [TAG], summary: '设置端点状态', description: '启用/禁用/暂停端点,启用时重置失败统计',
56
+ body: { type: 'object', properties: { id: any('端点 ID'), status: { type: 'string', enum: ['active', 'disabled', 'paused'] }, reason: str('禁用原因') }, required: ['id', 'status'] },
57
+ response: success('操作成功', endpoint) }
58
+ }, async request => services.endpoint.setStatus(auth(request), request.body));
59
+
60
+ fastify.post(`${options.prefix}/endpoint/rotate-secret`, {
61
+ onRequest: w,
62
+ schema: { tags: [TAG], summary: '轮换签名密钥', description: '轮换端点签名密钥,返回新的明文密钥(仅此一次)',
63
+ body: { type: 'object', properties: { id: any('端点 ID') }, required: ['id'] },
64
+ response: success('轮换成功', { type: 'object', properties: { secret: str('新签名密钥') } }) }
65
+ }, async request => services.endpoint.rotateSecret(auth(request), request.body));
66
+
67
+ fastify.get(`${options.prefix}/endpoint/list`, {
68
+ onRequest: r,
69
+ schema: { tags: [TAG], summary: '端点列表', description: '分页查询端点,支持按应用/状态/形态过滤',
70
+ querystring: { type: 'object', properties: { applicationId: any('应用 ID'), status: str('状态'), kind: str('形态'), direction: str('方向'), name: str('名称'), currentPage: { type: 'number' }, perPage: { type: 'number' } } },
71
+ response: success('查询成功', endpointList) }
72
+ }, async request => services.endpoint.list(auth(request), request.query));
73
+
74
+ fastify.get(`${options.prefix}/endpoint/detail`, {
75
+ onRequest: r,
76
+ schema: { tags: [TAG], summary: '端点详情', description: '按 id 或 uid 查询端点',
77
+ querystring: { type: 'object', properties: { id: any('端点 ID'), uid: str('外部 ID') } },
78
+ response: success('查询成功', endpoint) }
79
+ }, async request => services.endpoint.detail(auth(request), request.query));
80
+
81
+ fastify.post(`${options.prefix}/endpoint/test`, {
82
+ onRequest: w,
83
+ schema: { tags: [TAG], summary: '发送测试事件', description: '向指定端点发送一条测试消息',
84
+ body: { type: 'object', properties: { applicationId: any('应用 ID'), eventType: str('事件类型'), payload: { type: 'object', description: '测试 payload' } }, required: ['applicationId'] },
85
+ response: success('发送成功', { type: 'object', additionalProperties: true }) }
86
+ }, async request => {
87
+ const { applicationId, eventType = 'test.event', payload = {} } = request.body;
88
+ return services.message.create(auth(request), { applicationId, type: eventType, payload }, { source: 'test' });
89
+ });
90
+ });
@@ -0,0 +1,84 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const { any, str, success, empty, eventType, eventTypeList } = require('../schema/response');
5
+ const { auth: buildAuth, getAuthenticate: buildAuthenticate } = require('./_helper');
6
+
7
+ const TAG = 'Webhook-事件类型';
8
+
9
+ module.exports = fp(async (fastify, options) => {
10
+ const { services } = fastify[options.name];
11
+ const auth = request => buildAuth(options, request);
12
+ const w = buildAuthenticate(options, 'write');
13
+ const r = buildAuthenticate(options, 'read');
14
+
15
+ const props = {
16
+ name: str('事件类型名'), displayName: str('展示名称'), description: str('描述'),
17
+ descriptionTranslations: { type: 'object', description: '多语言描述' },
18
+ schema: { type: 'object', description: 'JSON Schema Draft 7' },
19
+ examples: { type: 'array', items: {}, description: '示例 payload' },
20
+ featureFlags: { type: 'array', items: { type: 'string' }, description: 'feature flags' },
21
+ groupName: str('分组'), status: str('状态')
22
+ };
23
+
24
+ fastify.post(`${options.prefix}/event-type/create`, {
25
+ onRequest: w,
26
+ schema: { tags: [TAG], summary: '创建事件类型', description: '定义事件类型及其 Schema 与示例',
27
+ body: { type: 'object', properties: props, required: ['name'] }, response: success('创建成功', eventType) }
28
+ }, async request => services.eventType.create(auth(request), request.body));
29
+
30
+ fastify.post(`${options.prefix}/event-type/save`, {
31
+ onRequest: w,
32
+ schema: { tags: [TAG], summary: '保存事件类型', description: '更新事件类型定义',
33
+ body: { type: 'object', properties: { id: any('ID'), ...props }, required: ['id'] }, response: success('保存成功', eventType) }
34
+ }, async request => services.eventType.save(auth(request), request.body));
35
+
36
+ fastify.post(`${options.prefix}/event-type/remove`, {
37
+ onRequest: w,
38
+ schema: { tags: [TAG], summary: '删除事件类型', description: '删除事件类型定义',
39
+ body: { type: 'object', properties: { id: any('ID') }, required: ['id'] }, response: empty() }
40
+ }, async request => services.eventType.remove(auth(request), request.body));
41
+
42
+ fastify.get(`${options.prefix}/event-type/list`, {
43
+ onRequest: r,
44
+ schema: { tags: [TAG], summary: '事件类型列表', description: '分页查询事件类型',
45
+ querystring: { type: 'object', properties: { name: str('名称'), status: str('状态'), currentPage: { type: 'number' }, perPage: { type: 'number' } } },
46
+ response: success('查询成功', eventTypeList) }
47
+ }, async request => services.eventType.list(auth(request), request.query));
48
+
49
+ fastify.post(`${options.prefix}/event-type/copy`, {
50
+ onRequest: w,
51
+ schema: { tags: [TAG], summary: '复制事件类型到当前租户', description: '把全局事件目录复制到当前租户作用域后定制',
52
+ body: { type: 'object', properties: { id: any('事件类型 ID') }, required: ['id'] }, response: success('复制成功', eventType) }
53
+ }, async request => services.eventType.copyToTenant(auth(request), request.body));
54
+
55
+ fastify.get(`${options.prefix}/event-type/schema`, {
56
+ onRequest: r,
57
+ schema: { tags: [TAG], summary: '获取事件 Schema', description: '按名称获取单个事件类型的 Schema 与示例',
58
+ querystring: { type: 'object', properties: { name: { type: 'string', description: '事件类型名' } }, required: ['name'] },
59
+ response: success('查询成功', eventType) }
60
+ }, async request => {
61
+ const result = await services.eventType.list(auth(request), { name: request.query.name, perPage: 1 });
62
+ return result.pageData[0] || {};
63
+ });
64
+
65
+ fastify.get(`${options.prefix}/event-type/catalog`, {
66
+ schema: { tags: [TAG], summary: '公开事件目录', description: '公开可访问的事件目录,按 featureFlags 过滤可见事件',
67
+ querystring: { type: 'object', properties: { lang: str('语言'), featureFlags: { type: 'array', items: { type: 'string' } } } },
68
+ response: success('查询成功', { type: 'array', items: {} }) }
69
+ }, async request => services.eventType.getCatalog(auth(request), request.query));
70
+
71
+ fastify.post(`${options.prefix}/event-type/import-openapi`, {
72
+ onRequest: w,
73
+ schema: { tags: [TAG], summary: '导入 OpenAPI', description: '从 OpenAPI 3.1 文档的 webhooks / x-webhooks 段导入事件类型',
74
+ body: { type: 'object', properties: { document: { type: 'object', description: 'OpenAPI 文档对象' } }, required: ['document'] },
75
+ response: success('导入成功', { type: 'object', additionalProperties: true }) }
76
+ }, async request => services.eventType.importOpenApi(auth(request), request.body));
77
+
78
+ fastify.post(`${options.prefix}/event-type/generate-sdk`, {
79
+ onRequest: r,
80
+ schema: { tags: [TAG], summary: '生成类型化客户端', description: '基于事件 Schema 生成 TypeScript 类型定义代码',
81
+ body: { type: 'object', properties: { lang: str('语言') } },
82
+ response: success('生成成功', { type: 'object', properties: { typescript: str('TS 类型定义') } }) }
83
+ }, async request => services.eventType.generateTypes(auth(request), request.body));
84
+ });