@lark-apaas/nestjs-trigger 0.0.1-alpha.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 ADDED
@@ -0,0 +1,576 @@
1
+ # @lark-apaas/nestjs-automation
2
+
3
+ 为 NestJS 应用提供声明式自动化任务注册与执行能力的核心模块。
4
+
5
+ 基于 TriggerClient 实现,提供 `@Automation`/`@BindTrigger` 装饰器、自动发现机制、REST 触发接口,以及与 trigger-server 的完整集成。
6
+
7
+ ## 目录
8
+
9
+ - [功能特性](#功能特性)
10
+ - [安装](#安装)
11
+ - [快速开始](#快速开始)
12
+ - [核心概念](#核心概念)
13
+ - [装饰器使用](#装饰器使用)
14
+ - [核心组件](#核心组件)
15
+ - [配置选项](#配置选项)
16
+ - [TriggerClient 接口](#triggerclient-接口)
17
+ - [与 trigger-server 集成](#与-trigger-server-集成)
18
+ - [开发与测试](#开发与测试)
19
+ - [许可证](#许可证)
20
+
21
+ ## 功能特性
22
+
23
+ - 🎯 **声明式 API** - 使用 `@Automation` 和 `@BindTrigger` 装饰器定义自动化任务
24
+ - 🔍 **自动发现** - 应用启动时自动扫描并注册所有自动化任务
25
+ - 📝 **强类型** - 完整的 TypeScript 类型定义与类型推断
26
+ - ⚡ **执行模式** - 支持同步和异步执行
27
+ - 🔒 **1:1 绑定** - 强制每个 triggerID 只能绑定一个方法,避免冲突
28
+ - 📡 **日志上报** - 集成观测系统,自动上报执行状态
29
+ - ⏱️ **超时控制** - 内置超时管理机制
30
+ - 📊 **日志跟踪** - 完整的执行生命周期日志记录
31
+
32
+ ## 安装
33
+
34
+ ```bash
35
+ npm install @lark-apaas/nestjs-automation
36
+ # 或
37
+ yarn add @lark-apaas/nestjs-automation
38
+ ```
39
+
40
+ ## 快速开始
41
+
42
+ ### 1. 导入模块
43
+
44
+ 在根模块中导入 `AutomationModule`:
45
+
46
+ ```typescript
47
+ import { Module } from '@nestjs/common';
48
+ import { AutomationModule } from '@lark-apaas/nestjs-automation';
49
+
50
+ @Module({
51
+ imports: [AutomationModule.forRoot()],
52
+ })
53
+ export class AppModule {}
54
+ ```
55
+
56
+ ### 2. 定义自动化任务
57
+
58
+ 使用 `@Automation()` 和 `@BindTrigger()` 装饰器定义任务:
59
+
60
+ ```typescript
61
+ import { Injectable } from '@nestjs/common';
62
+ import { Automation, BindTrigger } from '@lark-apaas/nestjs-automation';
63
+
64
+ @Automation()
65
+ @Injectable()
66
+ export class MyAutomationController {
67
+ /**
68
+ * 简单的问候任务
69
+ */
70
+ @BindTrigger('task-hello', {
71
+ actionName: 'HelloTask',
72
+ actionDesc: 'Print hello message'
73
+ })
74
+ async hello(name: string) {
75
+ return `Hello, ${name}!`;
76
+ }
77
+
78
+ /**
79
+ * 发送邮件通知任务
80
+ */
81
+ @BindTrigger('task-send-email', {
82
+ actionName: 'SendEmail',
83
+ actionDesc: 'Send notification email',
84
+ })
85
+ async sendEmail(to: string, subject: string, body: string) {
86
+ // 邮件发送逻辑
87
+ return { success: true, sentAt: new Date() };
88
+ }
89
+
90
+ /**
91
+ * 定时任务示例 - 每周五15:00执行
92
+ */
93
+ @BindTrigger('cron1[0 15 * * Fri]', {
94
+ actionName: 'SendWelcomeEmail',
95
+ actionDesc: '每周五15:00发送欢迎邮件'
96
+ })
97
+ async sendWeeklyEmail() {
98
+ // 每周五发送邮件逻辑
99
+ return { success: true, sentAt: new Date() };
100
+ }
101
+ }
102
+ ```
103
+
104
+ ### 3. 执行任务
105
+
106
+ 注入 `AutomationService` 来执行任务:
107
+
108
+ ```typescript
109
+ import { Injectable } from '@nestjs/common';
110
+ import { AutomationService } from '@lark-apaas/nestjs-automation';
111
+
112
+ @Injectable()
113
+ export class SomeService {
114
+ constructor(private readonly automation: AutomationService) {}
115
+
116
+ /**
117
+ * 同步执行任务并等待结果
118
+ */
119
+ async greet() {
120
+ const result = await this.automation.executeAction('task-hello', { name: 'world' });
121
+ console.log(result.result); // "Hello, world!"
122
+ return result;
123
+ }
124
+
125
+ /**
126
+ * 查询所有已注册的任务
127
+ */
128
+ getAllTasks() {
129
+ return this.automation.getAllActions();
130
+ }
131
+
132
+ /**
133
+ * 获取指定任务的详细信息
134
+ */
135
+ getTaskInfo(taskId: string) {
136
+ return this.automation.getActionInfo(taskId);
137
+ }
138
+ }
139
+ ```
140
+
141
+ ## 核心概念
142
+
143
+ ### 任务模型
144
+
145
+ 本模块采用以下任务模型:
146
+
147
+ - **Trigger** - 任务的唯一标识符,用于触发和执行任务
148
+ - **Action** - 具体的任务执行逻辑,由方法实现
149
+ - **Metadata** - 任务的元数据,包括名称、描述等信息
150
+ - **Context** - 任务执行的上下文,包含参数、租户ID等信息
151
+
152
+ ### 核心组件
153
+
154
+ | 组件 | 类型 | 说明 |
155
+ |------|------|------|
156
+ | `AutomationModule` | 模块 | 主模块,提供自动化功能 |
157
+ | `AutomationService` | 服务 | 提供任务执行、查询等API |
158
+ | `AutomationDiscoveryService` | 服务 | 自动发现并注册任务 |
159
+ | `AutomationController` | 控制器 | 提供REST触发接口 |
160
+ | `TriggerClient` | 客户端 | 与trigger-server通信的客户端 |
161
+ | `@Automation()` | 装饰器 | 标记自动化任务类 |
162
+ | `@BindTrigger()` | 装饰器 | 绑定任务方法到triggerID |
163
+
164
+ ## 装饰器使用
165
+
166
+ ### @Automation()
167
+
168
+ 类装饰器,标记一个类为自动化任务控制器。
169
+
170
+ **使用示例:**
171
+
172
+ ```typescript
173
+ @Automation()
174
+ @Injectable()
175
+ export class EmailAutomation {
176
+ // 任务方法定义
177
+ }
178
+ ```
179
+
180
+ ### @BindTrigger()
181
+
182
+ 方法装饰器,将方法绑定到指定的 trigger。
183
+
184
+ **参数:**
185
+
186
+ ```typescript
187
+ @BindTrigger(trigger: string, options?: {
188
+ actionName?: string; // 任务名称
189
+ actionDesc?: string; // 任务描述
190
+ })
191
+ ```
192
+
193
+ **使用示例:**
194
+
195
+ ```typescript
196
+ @Automation()
197
+ @Injectable()
198
+ export class NotificationAutomation {
199
+ @BindTrigger('cron1[0 15 * * Fri]', {
200
+ actionName: 'SendWelcomeEmail',
201
+ actionDesc: '每周五15:00发送欢迎邮件'
202
+ })
203
+ async sendWelcomeEmail(userId: string, email: string) {
204
+ // 发送欢迎邮件逻辑
205
+ return { success: true, userId };
206
+ }
207
+
208
+ @BindTrigger('process-payment', {
209
+ actionName: 'ProcessPayment',
210
+ actionDesc: 'Process user payment'
211
+ })
212
+ async processPayment(orderId: string, amount: number) {
213
+ // 处理支付逻辑
214
+ return { success: true, orderId, amount };
215
+ }
216
+ }
217
+ ```
218
+
219
+ **重要特性:**
220
+
221
+ - **1:1 绑定约束**:每个 trigger 只能绑定一个方法,重复绑定会抛出错误
222
+ - **自动注册**:应用启动时自动扫描并注册所有绑定的任务
223
+ - **类型安全**:支持完整的 TypeScript 类型推断
224
+
225
+ ## 核心组件
226
+
227
+ ### AutomationService
228
+
229
+ 提供任务执行和查询的核心API。
230
+
231
+ **主要方法:**
232
+
233
+ ```typescript
234
+ @Injectable()
235
+ export class MyService {
236
+ constructor(private readonly automation: AutomationService) {}
237
+
238
+ async executeTask() {
239
+ // 1. 执行任务
240
+ const result = await this.automation.executeAction(
241
+ 'task-hello',
242
+ { name: 'world' }
243
+ );
244
+
245
+ // 2. 检查任务是否存在
246
+ const exists = this.automation.hasAction('task-hello');
247
+
248
+ // 3. 获取任务信息
249
+ const info = this.automation.getActionInfo('task-hello');
250
+
251
+ // 4. 获取所有任务
252
+ const allTasks = this.automation.getAllActions();
253
+
254
+ // 5. 获取单个任务
255
+ const task = this.automation.getAction('task-hello');
256
+ }
257
+ }
258
+ ```
259
+
260
+ **返回类型:**
261
+
262
+ ```typescript
263
+ interface ActionExecutionResult {
264
+ trigger: string;
265
+ success: boolean;
266
+ result?: any;
267
+ error?: string;
268
+ startTime: Date;
269
+ endTime: Date;
270
+ duration: number;
271
+ }
272
+ ```
273
+
274
+ ### AutomationDiscoveryService
275
+
276
+ 自动发现并注册所有自动化任务。
277
+
278
+ **工作原理:**
279
+
280
+ 1. **模块初始化**:在 `onModuleInit()` 阶段启动扫描
281
+ 2. **类扫描**:查找所有带有 `@Automation()` 装饰器的类
282
+ 3. **方法扫描**:扫描类中带有 `@BindTrigger()` 装饰器的方法
283
+ 4. **自动注册**:将方法注册到 TriggerClient
284
+ 5. **冲突检测**:检查 triggerID 是否重复,确保 1:1 绑定
285
+
286
+ **生命周期:**
287
+
288
+ ```
289
+ Module Init → AutomationDiscoveryService.onModuleInit()
290
+ ↓
291
+ 扫描所有 @Automation() 类
292
+ ↓
293
+ 扫描 @BindTrigger() 方法
294
+ ↓
295
+ 注册到 TriggerClient
296
+ ↓
297
+ 任务可通过 AutomationService 执行
298
+ ```
299
+
300
+ **高级用法:**
301
+
302
+ ```typescript
303
+ @Injectable()
304
+ export class TaskManagementService {
305
+ constructor(private readonly discovery: AutomationDiscoveryService) {}
306
+
307
+ // 获取所有已注册的任务 ID
308
+ getAllRegisteredTasks(): string[] {
309
+ return this.discovery.getAllRegisteredTasks();
310
+ }
311
+
312
+ // 获取任务的元数据
313
+ getTaskMetadata(taskId: string) {
314
+ return this.discovery.getTaskMetadata(taskId);
315
+ // 返回: { name: string, path: string, desc?: string }
316
+ }
317
+ }
318
+ ```
319
+
320
+ ### AutomationController
321
+
322
+ 提供 REST API 接口,用于接收 trigger-server 的请求。
323
+
324
+ **接口详情:**
325
+
326
+ ```http
327
+ POST /innerapi/automation/invoke
328
+ ```
329
+
330
+ **请求头:**
331
+
332
+ ```
333
+ trigger-start-time: 1732567890123 # 触发开始时间戳(毫秒)
334
+ x-tenant-id: tenant_123 # 租户ID
335
+ ```
336
+
337
+ **请求体:**
338
+
339
+ ```json
340
+ {
341
+ "appid": "app_123",
342
+ "triggerID": "task-hello",
343
+ "instanceID": "inst_20251125_100023",
344
+ "params": {
345
+ "name": "world"
346
+ }
347
+ }
348
+ ```
349
+
350
+ **响应:**
351
+
352
+ ```json
353
+ {
354
+ "code": 200,
355
+ "message": ""
356
+ }
357
+ ```
358
+
359
+ **状态码说明:**
360
+
361
+ - `200`: 接收成功,异步执行
362
+ - `400`: 缺少必填字段
363
+ - `404`: triggerID 未注册
364
+ - `500`: 内部错误
365
+
366
+ ## 配置选项
367
+
368
+ 通过 `AutomationModule.forRoot(options)` 传入配置:
369
+
370
+ ```typescript
371
+ AutomationModule.forRoot({
372
+ timeout: 10_000, // 10秒超时
373
+ logEndpoint: 'https://observability.example.com', // 观测系统端点
374
+ imports: [ConfigModule], // 额外导入的模块
375
+ });
376
+ ```
377
+
378
+ ### 配置项说明
379
+
380
+ | 选项 | 类型 | 默认值 | 说明 |
381
+ |------|------|--------|------|
382
+ | `timeout` | `number` | `undefined` | 执行超时时间(毫秒) |
383
+ | `logEndpoint` | `string` | `undefined` | 观测系统日志上报端点 |
384
+ | `imports` | `Array<Type<any>\|DynamicModule\|Promise<DynamicModule>\|ForwardReference>` | `[]` | 额外导入的模块 |
385
+
386
+ ### 异步配置
387
+
388
+ 如果需要从 `ConfigService` 获取配置:
389
+
390
+ ```typescript
391
+ import { ConfigModule, ConfigService } from '@nestjs/config';
392
+
393
+ @Module({
394
+ imports: [
395
+ ConfigModule.forRoot(),
396
+ AutomationModule.forRootAsync({
397
+ imports: [ConfigModule],
398
+ inject: [ConfigService],
399
+ useFactory: async (configService: ConfigService) => ({
400
+ timeout: configService.get('AUTOMATION_TIMEOUT', 10_000),
401
+ logEndpoint: configService.get('OBSERVABILITY_ENDPOINT'),
402
+ }),
403
+ }),
404
+ ],
405
+ })
406
+ export class AppModule {}
407
+ ```
408
+
409
+ ## TriggerClient 接口
410
+
411
+ `TriggerClient` 是与 trigger-server 通信的核心客户端。
412
+
413
+ ### 主要功能
414
+
415
+ 1. **任务注册**:注册任务到客户端
416
+ 2. **任务执行**:执行指定任务
417
+ 3. **日志上报**:上报执行状态和日志到观测系统
418
+ 4. **超时管理**:管理任务执行超时
419
+
420
+ ### 日志上报
421
+
422
+ 自动上报以下信息到观测系统:
423
+
424
+ - **执行状态**:RECEIVED、SUCCEEDED、FAILED
425
+ - **执行信息**:任务ID、成功状态、结果、错误、耗时等
426
+ - **时间信息**:触发延迟、执行时长(秒级精确)
427
+
428
+ **上报数据格式:**
429
+
430
+ ```typescript
431
+ interface ReportData {
432
+ triggerID: string;
433
+ success: boolean;
434
+ result?: any;
435
+ error?: string;
436
+ startTime: Date;
437
+ endTime: Date;
438
+ duration: number;
439
+ }
440
+ ```
441
+
442
+ ## 与 trigger-server 集成
443
+
444
+ ### 集成架构
445
+
446
+ ```
447
+ Trigger Server → HTTP POST /innerapi/automation/invoke
448
+ ↓
449
+ AutomationController
450
+ ↓
451
+ AutomationService.executeAction()
452
+ ↓
453
+ TriggerClient.executeAction()
454
+ ↓
455
+ 实际任务方法执行
456
+ ↓
457
+ TriggerClient.report() → 观测系统
458
+ ```
459
+
460
+ ### 配置 logEndpoint
461
+
462
+ 在 `AutomationModule.forRoot()` 中配置 `logEndpoint`:
463
+
464
+ ```typescript
465
+ AutomationModule.forRoot({
466
+ logEndpoint: process.env.OBSERVABILITY_ENDPOINT,
467
+ timeout: 30_000,
468
+ });
469
+ ```
470
+
471
+ ### 执行流程
472
+
473
+ 1. **触发**:Trigger Server 发送 HTTP 请求到 `/innerapi/automation/invoke`
474
+ 2. **接收**:`AutomationController` 接收请求并验证参数
475
+ 3. **执行**:`AutomationService` 调用 `TriggerClient.executeAction()`
476
+ 4. **上报**:执行完成后,`TriggerClient` 自动上报日志到观测系统
477
+ 5. **响应**:返回 200 状态码,表示接收成功(异步执行)
478
+
479
+ ## 开发与测试
480
+
481
+ ### 本地开发
482
+
483
+ ```bash
484
+ # 安装依赖
485
+ yarn install
486
+
487
+ # 构建
488
+ yarn build
489
+
490
+ # 类型检查
491
+ yarn typecheck
492
+
493
+ # 运行测试
494
+ yarn test
495
+
496
+ # 监听模式
497
+ yarn test:watch
498
+ ```
499
+
500
+ ### 编写单元测试
501
+
502
+ ```typescript
503
+ import { Test, TestingModule } from '@nestjs/testing';
504
+ import { AutomationModule } from '@lark-apaas/nestjs-automation';
505
+ import { MyAutomation } from './my-automation';
506
+
507
+ describe('MyAutomation', () => {
508
+ let automation: MyAutomation;
509
+ let automationService: AutomationService;
510
+
511
+ beforeEach(async () => {
512
+ const module: TestingModule = await Test.createTestingModule({
513
+ imports: [AutomationModule.forRoot()],
514
+ providers: [MyAutomation],
515
+ }).compile();
516
+
517
+ automation = module.get<MyAutomation>(MyAutomation);
518
+ automationService = module.get<AutomationService>(AutomationService);
519
+ });
520
+
521
+ it('should execute task', async () => {
522
+ const result = await automationService.executeAction('task-hello', { name: 'test' });
523
+ expect(result.success).toBe(true);
524
+ expect(result.result).toBe('Hello, test!');
525
+ });
526
+ });
527
+ ```
528
+
529
+ ### 集成测试
530
+
531
+ ```typescript
532
+ import * as request from 'supertest';
533
+ import { Test } from '@nestjs/testing';
534
+ import { INestApplication } from '@nestjs/common';
535
+ import { AutomationModule } from '@lark-apaas/nestjs-automation';
536
+
537
+ describe('AutomationController (e2e)', () => {
538
+ let app: INestApplication;
539
+
540
+ beforeAll(async () => {
541
+ const moduleRef = await Test.createTestingModule({
542
+ imports: [AutomationModule.forRoot()],
543
+ }).compile();
544
+
545
+ app = moduleRef.createNestApplication();
546
+ await app.init();
547
+ });
548
+
549
+ it('/innerapi/automation/invoke (POST)', () => {
550
+ return request(app.getHttpServer())
551
+ .post('/innerapi/automation/invoke')
552
+ .set('trigger-start-time', Date.now().toString())
553
+ .set('x-tenant-id', 'test-tenant')
554
+ .send({
555
+ appid: 'test-app',
556
+ triggerID: 'task-hello',
557
+ instanceID: 'test-instance',
558
+ params: { name: 'world' },
559
+ })
560
+ .expect(200);
561
+ });
562
+
563
+ afterAll(async () => {
564
+ await app.close();
565
+ });
566
+ });
567
+ ```
568
+
569
+ ## 许可证
570
+
571
+ MIT
572
+
573
+ ## 相关链接
574
+
575
+ - [NestJS 文档](https://docs.nestjs.com/)
576
+ - [示例项目](../../examples/node-demo)