@aomex/kafka 0.0.0-stage → 4.7.1-alpha.2c491171.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/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/index.d.ts +362 -0
- package/dist/index.js +754 -0
- package/dist/index.js.map +1 -0
- package/package.json +43 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2023-2024 geekact
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @aomex/kafka
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
文档:https://aomex.js.org
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
import { DurationInput, Middleware, MixinMiddleware, Next, Service, Validator, ValidatorToken } from "@aomex/common";
|
|
2
|
+
import { GlobPathOptions } from "@aomex/internal-file-import";
|
|
3
|
+
import { NonReadonly, Union2Intersection } from "@aomex/internal-tools";
|
|
4
|
+
import { Logger } from "@aomex/logger";
|
|
5
|
+
import { ConnectionOptions } from "node:tls";
|
|
6
|
+
type KafkaMiddlewareToken<P extends object = object> = KafkaMiddleware<P> | MixinMiddleware<P>;
|
|
7
|
+
declare module '@aomex/common' {
|
|
8
|
+
interface MiddlewarePlatform<Deps extends object = object> {
|
|
9
|
+
readonly kafka: <Props extends object = object>(fn: KafkaMiddlewareArguments<Middleware.MergeDeps<Props, Deps>>['fn'] | KafkaMiddlewareArguments<Middleware.MergeDeps<Props, Deps>>) => object extends Deps ? KafkaMiddleware<Props> : KafkaMiddleware<Props> & {
|
|
10
|
+
_contextType: Middleware.WithDeps<Kafka.Context, Deps>;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
interface KafkaMiddlewareArguments<T extends object> {
|
|
15
|
+
fn: (ctx: NonReadonly<T> & Kafka.Context, next: Next) => any;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Kafka 消费专用中间件;`KafkaConsumer` / `createKafkaService` 的 `mount` 仅允许本类或 `mixin`。
|
|
19
|
+
*/
|
|
20
|
+
export declare class KafkaMiddleware<Props extends object = object> extends Middleware<Props> {
|
|
21
|
+
_contextType: Kafka.Context;
|
|
22
|
+
protected _kafka_middleware_: 'kafka-middleware';
|
|
23
|
+
constructor(args: KafkaMiddlewareArguments<Props>['fn'] | KafkaMiddlewareArguments<Props>);
|
|
24
|
+
}
|
|
25
|
+
type JsonPrimitive = string | number | boolean | null;
|
|
26
|
+
type Blocked = Date | RegExp | Function | Error | Map<unknown, unknown> | Set<unknown> | WeakMap<object, unknown> | WeakSet<object> | Promise<unknown> | ArrayBuffer | SharedArrayBuffer | DataView | bigint | symbol | undefined | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | BigUint64Array | Int8Array | Int16Array | Int32Array | BigInt64Array | Float32Array | Float64Array;
|
|
27
|
+
/**
|
|
28
|
+
* 主题消息体是否为可 JSON 序列化的值。
|
|
29
|
+
* 拒绝 Date、bigint、Buffer、函数、Map/Set 等编码后无法原样还原的类型。
|
|
30
|
+
*/
|
|
31
|
+
type IsKafkaValue<T> = T extends unknown ? [T] extends [JsonPrimitive] ? true : [T] extends [Blocked] ? false : [T] extends [readonly (infer Item)[]] ? [IsKafkaValue<Item>] extends [true] ? true : false : [T] extends [object] ? keyof T extends never ? true : [KafkaFieldFlags<T>] extends [true] ? true : false : false : false;
|
|
32
|
+
type KafkaFieldFlags<T> = { [K in keyof T]-?: IsKafkaField<T[K]>; }[keyof T];
|
|
33
|
+
type IsKafkaField<T> = [T] extends [undefined] ? false : [undefined] extends [T] ? IsKafkaValue<Exclude<T, undefined>> : IsKafkaValue<T>;
|
|
34
|
+
/**
|
|
35
|
+
* 一份主题契约:名字和校验规则。生产和消费都引用它。
|
|
36
|
+
* 请用 {@link defineKafkaTopic} 创建;构造函数为 `protected`,禁止业务侧直接 `new`。
|
|
37
|
+
* 建议放在 `src/topics/`,文件名以 `.topic.ts` 结尾,变量名以 `Topic` 结尾,
|
|
38
|
+
* 如 `order-created.topic.ts` 里的 `orderCreatedTopic`。
|
|
39
|
+
*/
|
|
40
|
+
export declare class KafkaTopic<T> {
|
|
41
|
+
readonly name: string;
|
|
42
|
+
readonly rule: ValidatorToken;
|
|
43
|
+
/** 仅用于把消息体类型留在实例上。 */
|
|
44
|
+
private readonly valueType;
|
|
45
|
+
protected constructor(name: string, rule: ValidatorToken);
|
|
46
|
+
/**
|
|
47
|
+
* 供 {@link defineKafkaTopic} 调用;带「消息体须可 JSON 还原」的类型门禁。
|
|
48
|
+
*/
|
|
49
|
+
protected static create<T extends ValidatorToken>(name: string, rule: IsKafkaValue<Validator.Infer<T>> extends true ? T : never): KafkaTopic<Validator.Infer<T>>;
|
|
50
|
+
/**
|
|
51
|
+
* 主题名须非空、不超过 249 字符,且只含字母、数字、`.`、`_`、`-`。
|
|
52
|
+
* 不能是 `.` 或 `..`。
|
|
53
|
+
*/
|
|
54
|
+
private static assertName;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* 声明一个主题。建议每个主题一个文件,放在 `src/topics/`,文件名以 `.topic.ts` 结尾。
|
|
58
|
+
*
|
|
59
|
+
* ```ts
|
|
60
|
+
* // src/topics/order-created.topic.ts
|
|
61
|
+
* export const orderCreatedTopic = defineKafkaTopic('order.created', {
|
|
62
|
+
* orderId: rule.string(),
|
|
63
|
+
* amount: rule.number(),
|
|
64
|
+
* });
|
|
65
|
+
* ```
|
|
66
|
+
*/
|
|
67
|
+
export declare function defineKafkaTopic<T extends ValidatorToken>(name: string, rule: IsKafkaValue<Validator.Infer<T>> extends true ? T : never): KafkaTopic<Validator.Infer<T>>;
|
|
68
|
+
/**
|
|
69
|
+
* 创建 Kafka 服务类,交给 `combineServices`。
|
|
70
|
+
*
|
|
71
|
+
* 同一个类同时给 Web 与 Console 用:Web 里 `produce`,Console 指令里 `consume`。
|
|
72
|
+
* 生产者在首次生产时连接,消费者在 `consume` 时连接,只发消息的进程不会加入消费组。
|
|
73
|
+
* 处理成功后提交下一条偏移量(至少一次)。处理函数抛错则不提交,并结束本次消费。
|
|
74
|
+
* 消费在 JSON 解析后按主题上的规则校验,失败同样不提交。
|
|
75
|
+
* WebApp / ConsoleApp 关停时调用 `onDestroy` 断开连接。
|
|
76
|
+
*
|
|
77
|
+
* 消息体必须是 JSON。Date、bigint、Buffer 等无法原样还原的规则会在类型上被拒绝。
|
|
78
|
+
* 需要别的编码时,传入 `encode` / `decode`。
|
|
79
|
+
*
|
|
80
|
+
* ```ts
|
|
81
|
+
* // src/topics/order-created.topic.ts
|
|
82
|
+
* export const orderCreatedTopic = defineKafkaTopic('order.created', {
|
|
83
|
+
* orderId: rule.string(),
|
|
84
|
+
* amount: rule.number(),
|
|
85
|
+
* });
|
|
86
|
+
*
|
|
87
|
+
* // src/consumers/order-created.consumer.ts
|
|
88
|
+
* import { orderCreatedTopic } from '../topics/order-created.topic.js';
|
|
89
|
+
* export const consumer = new KafkaConsumer({ groupId: 'billing' });
|
|
90
|
+
* consumer.on(orderCreatedTopic, {
|
|
91
|
+
* action: async (ctx) => {
|
|
92
|
+
* ctx.value.orderId;
|
|
93
|
+
* ctx.logger.info(ctx.recordKey);
|
|
94
|
+
* },
|
|
95
|
+
* });
|
|
96
|
+
*
|
|
97
|
+
* // src/services/kafka.service.ts
|
|
98
|
+
* export const KafkaService = createKafkaService({
|
|
99
|
+
* brokers: ['127.0.0.1:9092'],
|
|
100
|
+
* clientId: 'shop',
|
|
101
|
+
* logger,
|
|
102
|
+
* });
|
|
103
|
+
*
|
|
104
|
+
* // src/routers/order.router.ts
|
|
105
|
+
* await services.kafka.produce({
|
|
106
|
+
* topic: orderCreatedTopic,
|
|
107
|
+
* value: { orderId: '1', amount: 20 },
|
|
108
|
+
* });
|
|
109
|
+
* await services.kafka.consume('./src/consumers');
|
|
110
|
+
* ```
|
|
111
|
+
*/
|
|
112
|
+
export declare function createKafkaService<T extends KafkaMiddlewareToken[] | [] = []>(options: Kafka.Options<T>): new () => Service & Kafka.Service;
|
|
113
|
+
declare namespace Kafka {
|
|
114
|
+
/** `createKafkaService` 返回的实例。配置与连接不在这个表面上。 */
|
|
115
|
+
interface Service {
|
|
116
|
+
produce<T>(message: {
|
|
117
|
+
topic: KafkaTopic<T>;
|
|
118
|
+
value: NoInfer<T>;
|
|
119
|
+
} & SendOptions): Promise<readonly Receipt[]>;
|
|
120
|
+
produceMany<const T extends readonly unknown[]>(messages: { [I in keyof T]: {
|
|
121
|
+
topic: KafkaTopic<T[I]>;
|
|
122
|
+
value: NoInfer<T[I]>;
|
|
123
|
+
} & SendOptions; }): Promise<readonly Receipt[]>;
|
|
124
|
+
consume(source: ConsumeSource, options?: ConsumeOptions): Promise<void>;
|
|
125
|
+
}
|
|
126
|
+
type ConsumeSource = KafkaConsumer | readonly KafkaConsumer[] | GlobPathOptions;
|
|
127
|
+
interface ConsumeOptions {
|
|
128
|
+
/**
|
|
129
|
+
* 为 `true` 时,在没有已提交位点时从最早偏移量读;默认 `false`(从最新)。
|
|
130
|
+
* 已有提交位点时仍从提交处继续,不受本选项影响。
|
|
131
|
+
*/
|
|
132
|
+
fromBeginning?: boolean;
|
|
133
|
+
}
|
|
134
|
+
type Ssl = boolean | ConnectionOptions;
|
|
135
|
+
type Sasl = {
|
|
136
|
+
mechanism: 'plain';
|
|
137
|
+
username: string;
|
|
138
|
+
password: string;
|
|
139
|
+
} | {
|
|
140
|
+
mechanism: 'scram-sha-256';
|
|
141
|
+
username: string;
|
|
142
|
+
password: string;
|
|
143
|
+
} | {
|
|
144
|
+
mechanism: 'scram-sha-512';
|
|
145
|
+
username: string;
|
|
146
|
+
password: string;
|
|
147
|
+
} | {
|
|
148
|
+
mechanism: 'aws';
|
|
149
|
+
authorizationIdentity: string;
|
|
150
|
+
accessKeyId: string;
|
|
151
|
+
secretAccessKey: string;
|
|
152
|
+
sessionToken?: string;
|
|
153
|
+
} | {
|
|
154
|
+
mechanism: 'oauthbearer';
|
|
155
|
+
oauthBearerProvider: () => Promise<{
|
|
156
|
+
value: string;
|
|
157
|
+
}>;
|
|
158
|
+
};
|
|
159
|
+
/**
|
|
160
|
+
* 模块扩充点,可挂服务级推断类型:
|
|
161
|
+
*
|
|
162
|
+
* ```ts
|
|
163
|
+
* declare module '@aomex/kafka' {
|
|
164
|
+
* namespace Kafka {
|
|
165
|
+
* interface Props {
|
|
166
|
+
* traceId: string;
|
|
167
|
+
* }
|
|
168
|
+
* }
|
|
169
|
+
* }
|
|
170
|
+
* ```
|
|
171
|
+
*/
|
|
172
|
+
interface Props {}
|
|
173
|
+
interface Options<T extends KafkaMiddlewareToken[] | [] = []> {
|
|
174
|
+
/** broker 地址,如 `127.0.0.1:9092`。 */
|
|
175
|
+
brokers: readonly string[];
|
|
176
|
+
/**
|
|
177
|
+
* 应用日志。消费 `ctx.logger` 与此实例相同。
|
|
178
|
+
* 客户端内部日志(默认 `WARN`)也会经适配器写入本实例,不转发 `extra`。
|
|
179
|
+
*/
|
|
180
|
+
logger: Logger;
|
|
181
|
+
/**
|
|
182
|
+
* 本服务下所有消费共用的中间件(先于消费组 / 主题级 `mount` 执行)。
|
|
183
|
+
* 仅 `middleware.kafka` / `middleware.mixin`。
|
|
184
|
+
*/
|
|
185
|
+
mount?: T;
|
|
186
|
+
/**
|
|
187
|
+
* 客户端标识,任意非空字符串均可。会出现在 broker 日志与监控里,用于区分应用。
|
|
188
|
+
*/
|
|
189
|
+
clientId: string;
|
|
190
|
+
/**
|
|
191
|
+
* 传给连接层的 TLS 配置。不设则沿用客户端默认。
|
|
192
|
+
* 对象里的证书和私钥只接受 PEM 字符串、Buffer,或由它们组成的数组。
|
|
193
|
+
*/
|
|
194
|
+
ssl?: Ssl;
|
|
195
|
+
/**
|
|
196
|
+
* SASL 认证。不设则不认证。
|
|
197
|
+
* `aws` 当前客户端不支持,传入会在连接前抛错。
|
|
198
|
+
* `oauthbearer` 只需返回 `value`。
|
|
199
|
+
*/
|
|
200
|
+
sasl?: Sasl;
|
|
201
|
+
/**
|
|
202
|
+
* 连接超时。毫秒数或可读时长,如 `1_000`、`'1s'`。不设则沿用客户端默认。
|
|
203
|
+
*/
|
|
204
|
+
connectionTimeout?: DurationInput;
|
|
205
|
+
/**
|
|
206
|
+
* 请求超时。毫秒数或可读时长,如 `30_000`、`'30s'`。不设则沿用客户端默认。
|
|
207
|
+
*/
|
|
208
|
+
requestTimeout?: DurationInput;
|
|
209
|
+
/** 是否允许 broker 自动建主题。默认 `false`。 */
|
|
210
|
+
allowAutoTopicCreation?: boolean;
|
|
211
|
+
/**
|
|
212
|
+
* 幂等生产者。默认 `true`,此时 `acks` 必须为 `-1`。
|
|
213
|
+
* 开启后在途请求为 5,重试次数为 `(2 ** 31) - 1`,队列为先进先出。
|
|
214
|
+
*/
|
|
215
|
+
idempotent?: boolean;
|
|
216
|
+
/**
|
|
217
|
+
* 生产者确认级别。`-1` 全部副本,`1` 仅 leader,`0` 不等待。默认 `-1`。
|
|
218
|
+
*/
|
|
219
|
+
acks?: -1 | 0 | 1;
|
|
220
|
+
/**
|
|
221
|
+
* 单条消息(值、分区键、header)的字节上限。默认 1 MiB。
|
|
222
|
+
* 超过则拒绝发送,消费侧也拒绝解析。
|
|
223
|
+
* 传给客户端的协议上限与此相同,并限制在 1000 到 1000000000。
|
|
224
|
+
* 消费拉取上限只在这个值更大时上调。
|
|
225
|
+
*/
|
|
226
|
+
maxMessageBytes?: number;
|
|
227
|
+
/**
|
|
228
|
+
* 消费组会话超时。毫秒数或可读时长,如 `30_000`、`'30s'`。默认 `'30s'`。
|
|
229
|
+
*/
|
|
230
|
+
sessionTimeout?: DurationInput;
|
|
231
|
+
/**
|
|
232
|
+
* 处理消息期间自动心跳的间隔。毫秒数或可读时长,如 `3_000`、`'3s'`。
|
|
233
|
+
* 未设置时取 `min(3s, sessionTimeout / 3)`。
|
|
234
|
+
* 大于等于会话超时时拒绝创建。
|
|
235
|
+
* 小于等于 `0` 时本库不再按间隔调用心跳回调。客户端自己的会话心跳仍会继续。
|
|
236
|
+
*/
|
|
237
|
+
heartbeatInterval?: DurationInput;
|
|
238
|
+
/** 把消息体编码成字节。默认 JSON。 */
|
|
239
|
+
encode?: (value: unknown) => Buffer;
|
|
240
|
+
/** 把消息字节解成消息体。默认 JSON。 */
|
|
241
|
+
decode?: (buffer: Buffer) => unknown;
|
|
242
|
+
}
|
|
243
|
+
interface SendOptions {
|
|
244
|
+
/**
|
|
245
|
+
* 分区键。相同值进入同一分区,从而保证同键消息有序。
|
|
246
|
+
* 不传则由客户端分区器分配。
|
|
247
|
+
*/
|
|
248
|
+
partitionKey?: string;
|
|
249
|
+
/**
|
|
250
|
+
* 消息头:跟消息体分开的元数据,消费端在 `ctx.meta.headers` 读取。
|
|
251
|
+
* 典型用途:链路追踪(`traceId`)、报文版本、中间件按头过滤,而不必塞进业务 JSON。
|
|
252
|
+
* 键值均为字符串,会计入 `maxMessageBytes`;同一键多个值时消费侧只保留最后一个。
|
|
253
|
+
*/
|
|
254
|
+
headers?: Record<string, string>;
|
|
255
|
+
/** 指定分区编号。与 `partitionKey` 同时传时,以本字段为准。 */
|
|
256
|
+
partitionId?: number;
|
|
257
|
+
}
|
|
258
|
+
/** broker 对一条消息的回执。 */
|
|
259
|
+
interface Receipt {
|
|
260
|
+
/** 写入的主题名。 */
|
|
261
|
+
topic: string;
|
|
262
|
+
/** 写入的分区编号。 */
|
|
263
|
+
partitionId: number;
|
|
264
|
+
/** 写入后的偏移量;`acks` 为 `0` 或 broker 未返回时为 `null`。 */
|
|
265
|
+
offset: string | null;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* 消费到的消息位置与元数据,会出现在处理函数的 `ctx.meta` 上。
|
|
269
|
+
*/
|
|
270
|
+
interface Meta {
|
|
271
|
+
/** 主题名,与 `defineKafkaTopic` 登记的名字一致。 */
|
|
272
|
+
topic: string;
|
|
273
|
+
/** 实际落入的分区编号。 */
|
|
274
|
+
partitionId: number;
|
|
275
|
+
/** 本分区内的消息偏移量(字符串,避免超过 JS 安全整数)。 */
|
|
276
|
+
offset: string;
|
|
277
|
+
/** broker 侧消息时间戳(毫秒字符串)。 */
|
|
278
|
+
timestamp: string;
|
|
279
|
+
/**
|
|
280
|
+
* 生产时的分区键;未设置则为 `null`。
|
|
281
|
+
* 同键消息进同一分区,从而有序;不是业务单号。
|
|
282
|
+
*/
|
|
283
|
+
partitionKey: string | null;
|
|
284
|
+
/**
|
|
285
|
+
* 生产时附带的消息头;键值均为字符串。
|
|
286
|
+
* 同一键有多个值时只保留最后一个;没有头时为空对象。
|
|
287
|
+
*/
|
|
288
|
+
headers: Record<string, string>;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* 消费处理函数与 `middleware.kafka` 的上下文。
|
|
292
|
+
* `value` 为消息体,`recordKey` 为本条记录稳定标识,`meta` 为 broker 位置与消息元数据,
|
|
293
|
+
* `logger` 与 `createKafkaService` 传入的相同。`mount` 注入的属性也会出现在 `ctx` 上。
|
|
294
|
+
*/
|
|
295
|
+
type Context<T = unknown> = {
|
|
296
|
+
/** 经主题规则校验后的消息体。 */
|
|
297
|
+
value: T;
|
|
298
|
+
/** 与 `createKafkaService` 传入的相同;中间件与处理函数共用。 */
|
|
299
|
+
logger: Logger;
|
|
300
|
+
/**
|
|
301
|
+
* 本消费组视角下这条记录的稳定标识:`groupId:主题:分区:偏移量`,
|
|
302
|
+
* 如 `billing:order.created:0:9`。用于日志关联或去重键,不是分区键,也不是业务单号。
|
|
303
|
+
*/
|
|
304
|
+
recordKey: string;
|
|
305
|
+
/** broker 侧位置与消息元数据(主题、分区、偏移量、头等)。 */
|
|
306
|
+
meta: Meta;
|
|
307
|
+
} & Props;
|
|
308
|
+
type Handler<T> = (ctx: Context<T>) => void | Promise<void>;
|
|
309
|
+
}
|
|
310
|
+
type KafkaHandler = {
|
|
311
|
+
topic: KafkaTopic<unknown>;
|
|
312
|
+
middlewareList: KafkaMiddlewareToken[];
|
|
313
|
+
action: (ctx: Kafka.Context<unknown>) => void | Promise<void>;
|
|
314
|
+
};
|
|
315
|
+
interface KafkaConsumerOptions<T extends KafkaMiddlewareToken[] | [] = []> {
|
|
316
|
+
/**
|
|
317
|
+
* 消费组 ID。同组消费者共同分摊分区;同一次 `consume` 合并的多个实例必须相同。
|
|
318
|
+
*/
|
|
319
|
+
groupId: string;
|
|
320
|
+
/**
|
|
321
|
+
* 本消费组下所有主题共用的中间件(先于主题级 `mount` 执行)。
|
|
322
|
+
* 仅 `middleware.kafka` / `middleware.mixin`。
|
|
323
|
+
*/
|
|
324
|
+
mount?: T;
|
|
325
|
+
}
|
|
326
|
+
interface KafkaHandlerOptions<Value, Props extends object | unknown, T extends KafkaMiddlewareToken[] | []> {
|
|
327
|
+
/**
|
|
328
|
+
* 为 `true` 时不登记该主题(便于按环境开关)。
|
|
329
|
+
*/
|
|
330
|
+
disabled?: boolean;
|
|
331
|
+
/**
|
|
332
|
+
* 仅本主题的中间件。仅 `middleware.kafka` / `middleware.mixin`。
|
|
333
|
+
*/
|
|
334
|
+
mount?: T;
|
|
335
|
+
/**
|
|
336
|
+
* 消费处理函数;`ctx` 类型会合并消费组 / 主题级 `mount` 的 Props,并始终带 `logger`。
|
|
337
|
+
*/
|
|
338
|
+
action: (ctx: KafkaConsumer.Context<Value, Props, T>) => void | Promise<void>;
|
|
339
|
+
}
|
|
340
|
+
export declare namespace KafkaConsumer {
|
|
341
|
+
type Interface<Props extends object | unknown, T extends KafkaMiddlewareToken[] | []> = T extends [] ? Props : Props & Union2Intersection<Middleware.CollectArrayType<T[number]>>;
|
|
342
|
+
type Context<Value, Props extends object | unknown, T extends KafkaMiddlewareToken[] | []> = Kafka.Context<Value> & Interface<Props, T>;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* 一个消费组上的主题登记,用法对齐路由:先 `new`,再 `on`。
|
|
346
|
+
* 建议放在 `src/consumers/`,主题从 `src/topics/*.topic.ts` 引入。
|
|
347
|
+
* 同一目录里的多个实例交给 `consume` 合并,且必须是同一个 `groupId`。
|
|
348
|
+
*/
|
|
349
|
+
export declare class KafkaConsumer<T extends KafkaMiddlewareToken[] | [] = [], Props extends object | unknown = Kafka.Props & (T extends [] ? object : Union2Intersection<Middleware.CollectArrayType<T[number]>>)> {
|
|
350
|
+
readonly groupId: string;
|
|
351
|
+
private readonly middlewareList;
|
|
352
|
+
private readonly handlers;
|
|
353
|
+
constructor(options: KafkaConsumerOptions<T>);
|
|
354
|
+
/**
|
|
355
|
+
* 登记一个主题。`action` 收到 `ctx`,其中 `value` 从该主题的规则推断。
|
|
356
|
+
* 同一个实例里主题名不能重复。
|
|
357
|
+
* `disabled: true` 时不登记。
|
|
358
|
+
*/
|
|
359
|
+
on<V, M extends KafkaMiddlewareToken[] | [] = []>(topic: KafkaTopic<V>, options: KafkaHandlerOptions<V, Props, M>): void;
|
|
360
|
+
protected collect(): readonly KafkaHandler[];
|
|
361
|
+
}
|
|
362
|
+
export type { Kafka, KafkaConsumerOptions, KafkaHandlerOptions, KafkaMiddlewareToken };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,754 @@
|
|
|
1
|
+
import { I18n, Middleware, Service, compose, createI18n, middleware, parseDuration, validate } from "@aomex/common";
|
|
2
|
+
import { getFileValues, pathToFiles } from "@aomex/internal-file-import";
|
|
3
|
+
import { KafkaJS } from "@confluentinc/kafka-javascript";
|
|
4
|
+
// src/i18n/locales/zh-cn.ts
|
|
5
|
+
const zh = I18n.define({
|
|
6
|
+
empty_brokers: "brokers 不能为空",
|
|
7
|
+
empty_broker: "brokers 含有空地址",
|
|
8
|
+
empty_client_id: "clientId 不能为空",
|
|
9
|
+
empty_group_id: "groupId 不能为空",
|
|
10
|
+
empty_topic: "主题名不能为空",
|
|
11
|
+
invalid_topic_name: "非法的主题名:{{topic}}",
|
|
12
|
+
topic_name_too_long: "主题名过长:{{length}} > {{max}}",
|
|
13
|
+
duplicate_topic: "主题重复登记:{{topic}}",
|
|
14
|
+
mixed_group_id: "同一次消费只能有一个 groupId",
|
|
15
|
+
empty_consumers: "没有找到 Kafka 消费者",
|
|
16
|
+
already_consuming: "已有消费者在运行",
|
|
17
|
+
closed: "Kafka 连接已关闭",
|
|
18
|
+
message_too_large: "消息大小超过限制:{{bytes}} > {{max}}",
|
|
19
|
+
invalid_json: "消息不是合法的 JSON",
|
|
20
|
+
empty_message: "消息体为空",
|
|
21
|
+
encode_failed: "消息无法编码为 JSON",
|
|
22
|
+
unknown_topic: "收到未订阅的主题:{{topic}}",
|
|
23
|
+
invalid_offset: "非法的消息偏移量:{{offset}}",
|
|
24
|
+
idempotent_requires_all_acks: "开启幂等生产者时 acks 必须为 -1",
|
|
25
|
+
unsupported_sasl: "不支持的 SASL 机制:{{mechanism}}",
|
|
26
|
+
unsupported_tls: "TLS 配置无法交给客户端:{{name}}",
|
|
27
|
+
heartbeat_exceeds_session: "心跳间隔必须小于会话超时"
|
|
28
|
+
});
|
|
29
|
+
// src/i18n/locales/en-us.ts
|
|
30
|
+
const en = I18n.satisfies(zh).define({
|
|
31
|
+
empty_brokers: "brokers must not be empty",
|
|
32
|
+
empty_broker: "brokers contains an empty address",
|
|
33
|
+
empty_client_id: "clientId must not be empty",
|
|
34
|
+
empty_group_id: "groupId must not be empty",
|
|
35
|
+
empty_topic: "Topic name must not be empty",
|
|
36
|
+
invalid_topic_name: "Invalid topic name: {{topic}}",
|
|
37
|
+
topic_name_too_long: "Topic name is too long: {{length}} > {{max}}",
|
|
38
|
+
duplicate_topic: "Topic is registered more than once: {{topic}}",
|
|
39
|
+
mixed_group_id: "One consume call must use a single groupId",
|
|
40
|
+
empty_consumers: "No Kafka consumers were found",
|
|
41
|
+
already_consuming: "A consumer is already running",
|
|
42
|
+
closed: "Kafka connection is closed",
|
|
43
|
+
message_too_large: "Message exceeds the size limit: {{bytes}} > {{max}}",
|
|
44
|
+
invalid_json: "Message is not valid JSON",
|
|
45
|
+
empty_message: "Message payload is empty",
|
|
46
|
+
encode_failed: "Message could not be encoded as JSON",
|
|
47
|
+
unknown_topic: "Received an unsubscribed topic: {{topic}}",
|
|
48
|
+
invalid_offset: "Invalid message offset: {{offset}}",
|
|
49
|
+
idempotent_requires_all_acks: "acks must be -1 when the idempotent producer is enabled",
|
|
50
|
+
unsupported_sasl: "Unsupported SASL mechanism: {{mechanism}}",
|
|
51
|
+
unsupported_tls: "TLS option cannot be passed to the client: {{name}}",
|
|
52
|
+
heartbeat_exceeds_session: "Heartbeat interval must be less than the session timeout"
|
|
53
|
+
});
|
|
54
|
+
// src/i18n/index.ts
|
|
55
|
+
const i18n = createI18n({
|
|
56
|
+
zh,
|
|
57
|
+
en,
|
|
58
|
+
load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href)
|
|
59
|
+
});
|
|
60
|
+
// src/override/kafka-middleware.ts
|
|
61
|
+
/**
|
|
62
|
+
* Kafka 消费专用中间件;`KafkaConsumer` / `createKafkaService` 的 `mount` 仅允许本类或 `mixin`。
|
|
63
|
+
*/
|
|
64
|
+
var KafkaMiddleware = class extends Middleware {
|
|
65
|
+
constructor(args) {
|
|
66
|
+
const { fn } = typeof args === "function" ? { fn: args } : args;
|
|
67
|
+
super(fn);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
Middleware.register("kafka", KafkaMiddleware);
|
|
71
|
+
// src/core/consumer.ts
|
|
72
|
+
/**
|
|
73
|
+
* 一个消费组上的主题登记,用法对齐路由:先 `new`,再 `on`。
|
|
74
|
+
* 建议放在 `src/consumers/`,主题从 `src/topics/*.topic.ts` 引入。
|
|
75
|
+
* 同一目录里的多个实例交给 `consume` 合并,且必须是同一个 `groupId`。
|
|
76
|
+
*/
|
|
77
|
+
var KafkaConsumer = class {
|
|
78
|
+
groupId;
|
|
79
|
+
middlewareList;
|
|
80
|
+
handlers = [];
|
|
81
|
+
constructor(options) {
|
|
82
|
+
if (options.groupId.length === 0) throw new Error(i18n.t("empty_group_id"));
|
|
83
|
+
this.groupId = options.groupId;
|
|
84
|
+
this.middlewareList = options.mount || [];
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* 登记一个主题。`action` 收到 `ctx`,其中 `value` 从该主题的规则推断。
|
|
88
|
+
* 同一个实例里主题名不能重复。
|
|
89
|
+
* `disabled: true` 时不登记。
|
|
90
|
+
*/
|
|
91
|
+
on(topic, options) {
|
|
92
|
+
if (options.disabled === true) return;
|
|
93
|
+
if (this.handlers.some((item) => item.topic.name === topic.name)) throw new Error(i18n.t("duplicate_topic", { topic: topic.name }));
|
|
94
|
+
this.handlers.push({
|
|
95
|
+
topic,
|
|
96
|
+
middlewareList: [...this.middlewareList, ...options.mount || []],
|
|
97
|
+
action: options.action
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
collect() {
|
|
101
|
+
return this.handlers;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
// src/core/kafka.ts
|
|
105
|
+
/** 解析成毫秒。客户端只接受整数。 */
|
|
106
|
+
function durationMs(value) {
|
|
107
|
+
return Math.round(parseDuration(value));
|
|
108
|
+
}
|
|
109
|
+
/** 配置在工厂里校验一次。`combineServices` 只能 `new Ctor()`,所以结果是零参类。 */
|
|
110
|
+
function resolveOptions(options) {
|
|
111
|
+
if (options.brokers.length === 0) throw new Error(i18n.t("empty_brokers"));
|
|
112
|
+
const brokers = [];
|
|
113
|
+
for (const broker of options.brokers) {
|
|
114
|
+
if (broker.length === 0) throw new Error(i18n.t("empty_broker"));
|
|
115
|
+
brokers.push(broker);
|
|
116
|
+
}
|
|
117
|
+
const idempotent = options.idempotent ?? true;
|
|
118
|
+
const acks = options.acks ?? -1;
|
|
119
|
+
if (idempotent && acks !== -1) throw new Error(i18n.t("idempotent_requires_all_acks"));
|
|
120
|
+
const sessionTimeout = durationMs(options.sessionTimeout ?? "30s");
|
|
121
|
+
const heartbeatInterval = options.heartbeatInterval === void 0 ? Math.min(durationMs("3s"), Math.max(1, Math.floor(sessionTimeout / 3))) : durationMs(options.heartbeatInterval);
|
|
122
|
+
if (heartbeatInterval > 0 && heartbeatInterval >= sessionTimeout) throw new Error(i18n.t("heartbeat_exceeds_session"));
|
|
123
|
+
if (options.clientId.length === 0) throw new Error(i18n.t("empty_client_id"));
|
|
124
|
+
return {
|
|
125
|
+
brokers,
|
|
126
|
+
clientId: options.clientId,
|
|
127
|
+
logger: options.logger,
|
|
128
|
+
mount: options.mount ?? [],
|
|
129
|
+
...options.ssl === void 0 ? {} : { ssl: options.ssl },
|
|
130
|
+
...options.sasl === void 0 ? {} : { sasl: options.sasl },
|
|
131
|
+
...options.connectionTimeout === void 0 ? {} : { connectionTimeout: durationMs(options.connectionTimeout) },
|
|
132
|
+
...options.requestTimeout === void 0 ? {} : { requestTimeout: durationMs(options.requestTimeout) },
|
|
133
|
+
allowAutoTopicCreation: options.allowAutoTopicCreation ?? false,
|
|
134
|
+
idempotent,
|
|
135
|
+
acks,
|
|
136
|
+
maxMessageBytes: options.maxMessageBytes ?? 1048576,
|
|
137
|
+
sessionTimeout,
|
|
138
|
+
heartbeatInterval,
|
|
139
|
+
...options.encode === void 0 ? {} : { encode: options.encode },
|
|
140
|
+
...options.decode === void 0 ? {} : { decode: options.decode }
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* 创建 Kafka 服务类,交给 `combineServices`。
|
|
145
|
+
*
|
|
146
|
+
* 同一个类同时给 Web 与 Console 用:Web 里 `produce`,Console 指令里 `consume`。
|
|
147
|
+
* 生产者在首次生产时连接,消费者在 `consume` 时连接,只发消息的进程不会加入消费组。
|
|
148
|
+
* 处理成功后提交下一条偏移量(至少一次)。处理函数抛错则不提交,并结束本次消费。
|
|
149
|
+
* 消费在 JSON 解析后按主题上的规则校验,失败同样不提交。
|
|
150
|
+
* WebApp / ConsoleApp 关停时调用 `onDestroy` 断开连接。
|
|
151
|
+
*
|
|
152
|
+
* 消息体必须是 JSON。Date、bigint、Buffer 等无法原样还原的规则会在类型上被拒绝。
|
|
153
|
+
* 需要别的编码时,传入 `encode` / `decode`。
|
|
154
|
+
*
|
|
155
|
+
* ```ts
|
|
156
|
+
* // src/topics/order-created.topic.ts
|
|
157
|
+
* export const orderCreatedTopic = defineKafkaTopic('order.created', {
|
|
158
|
+
* orderId: rule.string(),
|
|
159
|
+
* amount: rule.number(),
|
|
160
|
+
* });
|
|
161
|
+
*
|
|
162
|
+
* // src/consumers/order-created.consumer.ts
|
|
163
|
+
* import { orderCreatedTopic } from '../topics/order-created.topic.js';
|
|
164
|
+
* export const consumer = new KafkaConsumer({ groupId: 'billing' });
|
|
165
|
+
* consumer.on(orderCreatedTopic, {
|
|
166
|
+
* action: async (ctx) => {
|
|
167
|
+
* ctx.value.orderId;
|
|
168
|
+
* ctx.logger.info(ctx.recordKey);
|
|
169
|
+
* },
|
|
170
|
+
* });
|
|
171
|
+
*
|
|
172
|
+
* // src/services/kafka.service.ts
|
|
173
|
+
* export const KafkaService = createKafkaService({
|
|
174
|
+
* brokers: ['127.0.0.1:9092'],
|
|
175
|
+
* clientId: 'shop',
|
|
176
|
+
* logger,
|
|
177
|
+
* });
|
|
178
|
+
*
|
|
179
|
+
* // src/routers/order.router.ts
|
|
180
|
+
* await services.kafka.produce({
|
|
181
|
+
* topic: orderCreatedTopic,
|
|
182
|
+
* value: { orderId: '1', amount: 20 },
|
|
183
|
+
* });
|
|
184
|
+
* await services.kafka.consume('./src/consumers');
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
function createKafkaService(options) {
|
|
188
|
+
const settings = resolveOptions(options);
|
|
189
|
+
return class KafkaService extends KafkaRuntime {
|
|
190
|
+
constructor() {
|
|
191
|
+
super(settings);
|
|
192
|
+
}
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
var KafkaRuntime = class extends Service {
|
|
196
|
+
settings;
|
|
197
|
+
client;
|
|
198
|
+
producer;
|
|
199
|
+
producerReady;
|
|
200
|
+
consumer;
|
|
201
|
+
releaseTask;
|
|
202
|
+
consumption;
|
|
203
|
+
unbind = [];
|
|
204
|
+
consuming = false;
|
|
205
|
+
stopRequested = false;
|
|
206
|
+
/** 消费已失败:拦住并发 eachMessage 继续处理或提交。 */
|
|
207
|
+
consumeAborted = false;
|
|
208
|
+
closed = false;
|
|
209
|
+
constructor(settings) {
|
|
210
|
+
super();
|
|
211
|
+
this.settings = settings;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* 生产一条消息。返回 broker 回执;`acks` 为 `0` 时数组为空。
|
|
215
|
+
*/
|
|
216
|
+
async produce(message) {
|
|
217
|
+
this.assertOpen();
|
|
218
|
+
const wire = this.toMessage(message.value, message);
|
|
219
|
+
const metadata = await (await this.ensureProducer()).send({
|
|
220
|
+
topic: message.topic.name,
|
|
221
|
+
messages: [wire]
|
|
222
|
+
});
|
|
223
|
+
return this.toReceipts(metadata);
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* 一次生产多条消息,按主题分组提交。空数组直接返回。
|
|
227
|
+
* 回执顺序与 broker 响应一致,不保证与入参下标对齐。
|
|
228
|
+
* 单条形状与 `produce` 相同。
|
|
229
|
+
*/
|
|
230
|
+
async produceMany(messages) {
|
|
231
|
+
this.assertOpen();
|
|
232
|
+
if (messages.length === 0) return [];
|
|
233
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
234
|
+
for (const item of messages) {
|
|
235
|
+
const wire = this.toMessage(item.value, item);
|
|
236
|
+
const list = grouped.get(item.topic.name);
|
|
237
|
+
if (list) list.push(wire);
|
|
238
|
+
else grouped.set(item.topic.name, [wire]);
|
|
239
|
+
}
|
|
240
|
+
const metadata = await (await this.ensureProducer()).sendBatch({ topicMessages: [...grouped.entries()].map(([topic, batch]) => ({
|
|
241
|
+
topic,
|
|
242
|
+
messages: batch
|
|
243
|
+
})) });
|
|
244
|
+
return this.toReceipts(metadata);
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* 加入消费组并持续处理消息,直到进程关停或处理失败。
|
|
248
|
+
*
|
|
249
|
+
* 在 Console 指令里调用。不要放进 HTTP 请求:Promise 在关停前不会完成。
|
|
250
|
+
* 处理函数成功返回后才提交下一条偏移量。抛错则不提交,Promise 拒绝,进程应按失败退出。
|
|
251
|
+
* 同一实例不能并行消费;两个消费组请再 `createKafkaService` 一次。
|
|
252
|
+
*/
|
|
253
|
+
async consume(source, options) {
|
|
254
|
+
this.assertOpen();
|
|
255
|
+
if (this.consuming) throw new Error(i18n.t("already_consuming"));
|
|
256
|
+
this.consuming = true;
|
|
257
|
+
this.stopRequested = false;
|
|
258
|
+
this.consumeAborted = false;
|
|
259
|
+
let input;
|
|
260
|
+
let consumer;
|
|
261
|
+
const heartbeatInterval = this.settings.heartbeatInterval;
|
|
262
|
+
try {
|
|
263
|
+
input = this.subscriptions(await this.loadConsumers(source));
|
|
264
|
+
if (Object.keys(input.each).length === 0) {
|
|
265
|
+
this.consuming = false;
|
|
266
|
+
return;
|
|
267
|
+
}
|
|
268
|
+
consumer = this.createClient().consumer({ kafkaJS: {
|
|
269
|
+
groupId: input.groupId,
|
|
270
|
+
allowAutoTopicCreation: this.settings.allowAutoTopicCreation,
|
|
271
|
+
sessionTimeout: this.settings.sessionTimeout,
|
|
272
|
+
...heartbeatInterval > 0 ? { heartbeatInterval } : {},
|
|
273
|
+
fromBeginning: options?.fromBeginning ?? false,
|
|
274
|
+
autoCommit: false,
|
|
275
|
+
...this.consumerFetch()
|
|
276
|
+
} });
|
|
277
|
+
} catch (error) {
|
|
278
|
+
this.consuming = false;
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
this.consumer = consumer;
|
|
282
|
+
this.bindConsumer(consumer);
|
|
283
|
+
const done = this.beginConsumption();
|
|
284
|
+
try {
|
|
285
|
+
await consumer.connect();
|
|
286
|
+
await consumer.subscribe({ topics: Object.keys(input.each) });
|
|
287
|
+
await consumer.run({ eachMessage: async (payload) => {
|
|
288
|
+
if (this.consumeAborted) return;
|
|
289
|
+
try {
|
|
290
|
+
await this.handleMessage(payload, input.each, consumer, input.groupId);
|
|
291
|
+
} catch (error) {
|
|
292
|
+
this.abortConsumption(error);
|
|
293
|
+
throw error;
|
|
294
|
+
}
|
|
295
|
+
} });
|
|
296
|
+
await done;
|
|
297
|
+
} finally {
|
|
298
|
+
await this.releaseConsumer();
|
|
299
|
+
this.clearBindings();
|
|
300
|
+
this.finishConsumption();
|
|
301
|
+
this.consumption = void 0;
|
|
302
|
+
this.consuming = false;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/** 创建客户端。网络连接推迟到发送或消费。 */
|
|
306
|
+
async onInit() {
|
|
307
|
+
this.createClient();
|
|
308
|
+
}
|
|
309
|
+
/** 停止消费者并断开生产者。重复调用无效果。 */
|
|
310
|
+
async onDestroy() {
|
|
311
|
+
if (this.closed) return;
|
|
312
|
+
this.closed = true;
|
|
313
|
+
await this.releaseConsumer();
|
|
314
|
+
await this.releaseProducer();
|
|
315
|
+
}
|
|
316
|
+
createClient() {
|
|
317
|
+
if (this.client) return this.client;
|
|
318
|
+
this.assertOpen();
|
|
319
|
+
const { clientId, brokers, ssl, sasl, connectionTimeout, requestTimeout } = this.settings;
|
|
320
|
+
const config = {
|
|
321
|
+
"message.max.bytes": this.wireMessageMaxBytes(),
|
|
322
|
+
"kafkaJS": {
|
|
323
|
+
clientId,
|
|
324
|
+
brokers: [...brokers],
|
|
325
|
+
logLevel: KafkaJS.logLevel.WARN,
|
|
326
|
+
logger: this.toClientLogger(),
|
|
327
|
+
...ssl === void 0 ? {} : { ssl: ssl !== false },
|
|
328
|
+
...sasl === void 0 ? {} : { sasl: this.toSasl(sasl) },
|
|
329
|
+
...connectionTimeout === void 0 ? {} : { connectionTimeout },
|
|
330
|
+
...requestTimeout === void 0 ? {} : { requestTimeout }
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
this.applyTls(config);
|
|
334
|
+
this.client = new KafkaJS.Kafka(config);
|
|
335
|
+
return this.client;
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* 把应用 `logger` 适配成客户端 logger。
|
|
339
|
+
* 默认 `WARN`;只转发文案,不带 `extra`(可能含连接细节)。
|
|
340
|
+
*/
|
|
341
|
+
toClientLogger() {
|
|
342
|
+
const app = this.settings.logger;
|
|
343
|
+
let current = KafkaJS.logLevel.WARN;
|
|
344
|
+
const logger = {
|
|
345
|
+
setLogLevel: (next) => {
|
|
346
|
+
current = next;
|
|
347
|
+
},
|
|
348
|
+
namespace: () => logger,
|
|
349
|
+
info: (message) => {
|
|
350
|
+
if (current >= KafkaJS.logLevel.INFO) app.info(message);
|
|
351
|
+
},
|
|
352
|
+
warn: (message) => {
|
|
353
|
+
if (current >= KafkaJS.logLevel.WARN) app.warn(message);
|
|
354
|
+
},
|
|
355
|
+
error: (message) => {
|
|
356
|
+
if (current >= KafkaJS.logLevel.ERROR) app.error(message);
|
|
357
|
+
},
|
|
358
|
+
debug: (message) => {
|
|
359
|
+
if (current >= KafkaJS.logLevel.DEBUG) app.debug(message);
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
return logger;
|
|
363
|
+
}
|
|
364
|
+
/** 把 TLS 对象映射成客户端认识的证书项。布尔值只表示开关。 */
|
|
365
|
+
applyTls(config) {
|
|
366
|
+
const ssl = this.settings.ssl;
|
|
367
|
+
if (ssl == null || typeof ssl !== "object") return;
|
|
368
|
+
if (ssl.rejectUnauthorized === false) config["enable.ssl.certificate.verification"] = false;
|
|
369
|
+
const ca = this.pem(ssl.ca, "ca");
|
|
370
|
+
if (ca !== void 0) config["ssl.ca.pem"] = ca;
|
|
371
|
+
const cert = this.pem(ssl.cert, "cert");
|
|
372
|
+
if (cert !== void 0) config["ssl.certificate.pem"] = cert;
|
|
373
|
+
const key = this.pem(ssl.key, "key");
|
|
374
|
+
if (key !== void 0) config["ssl.key.pem"] = key;
|
|
375
|
+
if (typeof ssl.passphrase === "string") config["ssl.key.password"] = ssl.passphrase;
|
|
376
|
+
}
|
|
377
|
+
pem(value, name) {
|
|
378
|
+
if (value == null) return void 0;
|
|
379
|
+
if (typeof value === "string") return value;
|
|
380
|
+
if (Buffer.isBuffer(value)) return value.toString("utf8");
|
|
381
|
+
if (Array.isArray(value)) return value.map((item) => this.pem(item, name) ?? "").join("\n");
|
|
382
|
+
throw new Error(i18n.t("unsupported_tls", { name }));
|
|
383
|
+
}
|
|
384
|
+
toSasl(sasl) {
|
|
385
|
+
if (sasl.mechanism === "aws") throw new Error(i18n.t("unsupported_sasl", { mechanism: "aws" }));
|
|
386
|
+
if (sasl.mechanism === "oauthbearer") {
|
|
387
|
+
const provide = sasl.oauthBearerProvider;
|
|
388
|
+
return {
|
|
389
|
+
mechanism: "oauthbearer",
|
|
390
|
+
oauthBearerProvider: async () => {
|
|
391
|
+
return {
|
|
392
|
+
value: (await provide()).value,
|
|
393
|
+
principal: "",
|
|
394
|
+
lifetime: Date.now() + 36e5
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
return sasl;
|
|
400
|
+
}
|
|
401
|
+
assertOpen() {
|
|
402
|
+
if (this.closed) throw new Error(i18n.t("closed"));
|
|
403
|
+
}
|
|
404
|
+
async ensureProducer() {
|
|
405
|
+
this.assertOpen();
|
|
406
|
+
this.producerReady ??= this.connectProducer().catch((error) => {
|
|
407
|
+
this.producerReady = void 0;
|
|
408
|
+
throw error;
|
|
409
|
+
});
|
|
410
|
+
return this.producerReady;
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* 幂等开启时补上客户端兼容层不会自动改写的参数:在途请求 5、重试 `(2 ** 31) - 1`、先进先出。
|
|
414
|
+
* 每次生产都等待回执,不等待攒批。
|
|
415
|
+
*/
|
|
416
|
+
producerConfig() {
|
|
417
|
+
const kafkaJS = {
|
|
418
|
+
idempotent: this.settings.idempotent,
|
|
419
|
+
allowAutoTopicCreation: this.settings.allowAutoTopicCreation,
|
|
420
|
+
acks: this.settings.acks
|
|
421
|
+
};
|
|
422
|
+
const config = {
|
|
423
|
+
kafkaJS,
|
|
424
|
+
"linger.ms": 0
|
|
425
|
+
};
|
|
426
|
+
if (!this.settings.idempotent) return config;
|
|
427
|
+
kafkaJS.maxInFlightRequests = 5;
|
|
428
|
+
kafkaJS.retry = { retries: 2 ** 31 - 1 };
|
|
429
|
+
config["queuing.strategy"] = "fifo";
|
|
430
|
+
return config;
|
|
431
|
+
}
|
|
432
|
+
/** 协议报文上限。客户端只接受 1000 到 1000000000。 */
|
|
433
|
+
wireMessageMaxBytes() {
|
|
434
|
+
const bytes = this.settings.maxMessageBytes;
|
|
435
|
+
if (bytes < 1e3) return 1e3;
|
|
436
|
+
if (bytes > 1e9) return 1e9;
|
|
437
|
+
return bytes;
|
|
438
|
+
}
|
|
439
|
+
/** 拉取上限只在允许的报文更大时上调。 */
|
|
440
|
+
consumerFetch() {
|
|
441
|
+
const bytes = this.wireMessageMaxBytes();
|
|
442
|
+
return {
|
|
443
|
+
...bytes > 1048576 ? { maxBytesPerPartition: bytes } : {},
|
|
444
|
+
...bytes > 10485760 ? { maxBytes: bytes } : {}
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
async connectProducer() {
|
|
448
|
+
const producer = this.createClient().producer(this.producerConfig());
|
|
449
|
+
this.producer = producer;
|
|
450
|
+
try {
|
|
451
|
+
await producer.connect();
|
|
452
|
+
} catch (error) {
|
|
453
|
+
this.producer = void 0;
|
|
454
|
+
await producer.disconnect().catch(() => void 0);
|
|
455
|
+
throw error;
|
|
456
|
+
}
|
|
457
|
+
if (this.closed) throw new Error(i18n.t("closed"));
|
|
458
|
+
return producer;
|
|
459
|
+
}
|
|
460
|
+
async releaseProducer() {
|
|
461
|
+
const producer = this.producer;
|
|
462
|
+
this.producer = void 0;
|
|
463
|
+
this.producerReady = void 0;
|
|
464
|
+
if (!producer) return;
|
|
465
|
+
await producer.disconnect();
|
|
466
|
+
}
|
|
467
|
+
toMessage(value, options) {
|
|
468
|
+
const encoded = this.encodeValue(value);
|
|
469
|
+
let size = encoded.byteLength;
|
|
470
|
+
if (options?.partitionKey !== void 0) size += Buffer.byteLength(options.partitionKey);
|
|
471
|
+
if (options?.headers) for (const [name, header] of Object.entries(options.headers)) size += Buffer.byteLength(name) + Buffer.byteLength(header);
|
|
472
|
+
this.assertSize(size);
|
|
473
|
+
return {
|
|
474
|
+
value: encoded,
|
|
475
|
+
...options?.partitionKey === void 0 ? {} : { key: options.partitionKey },
|
|
476
|
+
...options?.headers === void 0 ? {} : { headers: options.headers },
|
|
477
|
+
...options?.partitionId === void 0 ? {} : { partition: options.partitionId }
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
/** 默认 JSON。`encode` 的返回值仍受 `maxMessageBytes` 约束。 */
|
|
481
|
+
encodeValue(value) {
|
|
482
|
+
const encode = this.settings.encode;
|
|
483
|
+
if (encode) return encode(value);
|
|
484
|
+
let json;
|
|
485
|
+
try {
|
|
486
|
+
json = JSON.stringify(value);
|
|
487
|
+
} catch (error) {
|
|
488
|
+
throw new Error(i18n.t("encode_failed"), { cause: error });
|
|
489
|
+
}
|
|
490
|
+
if (typeof json !== "string") throw new Error(i18n.t("encode_failed"));
|
|
491
|
+
return Buffer.from(json);
|
|
492
|
+
}
|
|
493
|
+
/** 默认 JSON。解析失败抛出固定文案。 */
|
|
494
|
+
decodeValue(buffer) {
|
|
495
|
+
const decode = this.settings.decode;
|
|
496
|
+
if (decode) return decode(buffer);
|
|
497
|
+
try {
|
|
498
|
+
return JSON.parse(buffer.toString("utf8"));
|
|
499
|
+
} catch (error) {
|
|
500
|
+
throw new Error(i18n.t("invalid_json"), { cause: error });
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
assertSize(bytes) {
|
|
504
|
+
if (bytes > this.settings.maxMessageBytes) throw new Error(i18n.t("message_too_large", {
|
|
505
|
+
bytes: String(bytes),
|
|
506
|
+
max: String(this.settings.maxMessageBytes)
|
|
507
|
+
}));
|
|
508
|
+
}
|
|
509
|
+
toReceipts(metadata) {
|
|
510
|
+
return metadata.map((item) => ({
|
|
511
|
+
topic: item.topicName,
|
|
512
|
+
partitionId: item.partition,
|
|
513
|
+
offset: item.offset ?? item.baseOffset ?? null
|
|
514
|
+
}));
|
|
515
|
+
}
|
|
516
|
+
beginConsumption() {
|
|
517
|
+
const { promise, resolve, reject } = Promise.withResolvers();
|
|
518
|
+
this.consumption = {
|
|
519
|
+
resolve,
|
|
520
|
+
reject,
|
|
521
|
+
settled: false
|
|
522
|
+
};
|
|
523
|
+
return promise;
|
|
524
|
+
}
|
|
525
|
+
finishConsumption() {
|
|
526
|
+
const current = this.consumption;
|
|
527
|
+
if (!current || current.settled) return;
|
|
528
|
+
current.settled = true;
|
|
529
|
+
current.resolve();
|
|
530
|
+
}
|
|
531
|
+
failConsumption(error) {
|
|
532
|
+
const current = this.consumption;
|
|
533
|
+
if (!current || current.settled) return;
|
|
534
|
+
current.settled = true;
|
|
535
|
+
current.reject(error);
|
|
536
|
+
}
|
|
537
|
+
/** 标记消费失败、拒绝 `consume` Promise,并尽快断开,避免客户端继续拉取。 */
|
|
538
|
+
abortConsumption(error) {
|
|
539
|
+
this.consumeAborted = true;
|
|
540
|
+
this.failConsumption(error);
|
|
541
|
+
this.releaseConsumer();
|
|
542
|
+
}
|
|
543
|
+
bindConsumer(consumer) {
|
|
544
|
+
const events = consumer.events;
|
|
545
|
+
if (events == null || typeof consumer.on !== "function") return;
|
|
546
|
+
const listen = consumer.on.bind(consumer);
|
|
547
|
+
this.unbind.push(listen(events.CRASH, (event) => {
|
|
548
|
+
if (event.payload.restart) return;
|
|
549
|
+
this.abortConsumption(event.payload.error);
|
|
550
|
+
}), listen(events.STOP, () => {
|
|
551
|
+
if (!this.stopRequested) return;
|
|
552
|
+
this.finishConsumption();
|
|
553
|
+
}));
|
|
554
|
+
}
|
|
555
|
+
clearBindings() {
|
|
556
|
+
for (const off of this.unbind) off();
|
|
557
|
+
this.unbind = [];
|
|
558
|
+
}
|
|
559
|
+
releaseConsumer() {
|
|
560
|
+
if (this.releaseTask) return this.releaseTask;
|
|
561
|
+
const consumer = this.consumer;
|
|
562
|
+
const ending = this.consumption;
|
|
563
|
+
this.consumer = void 0;
|
|
564
|
+
this.stopRequested = true;
|
|
565
|
+
this.releaseTask = (consumer ? consumer.disconnect() : Promise.resolve()).finally(() => {
|
|
566
|
+
if (ending && !ending.settled) {
|
|
567
|
+
ending.settled = true;
|
|
568
|
+
ending.resolve();
|
|
569
|
+
}
|
|
570
|
+
this.releaseTask = void 0;
|
|
571
|
+
});
|
|
572
|
+
return this.releaseTask;
|
|
573
|
+
}
|
|
574
|
+
async loadConsumers(source) {
|
|
575
|
+
if (source instanceof KafkaConsumer) return [source];
|
|
576
|
+
if (this.isConsumerList(source)) return [...source];
|
|
577
|
+
const files = await pathToFiles(source);
|
|
578
|
+
return getFileValues(files, (item) => item instanceof KafkaConsumer);
|
|
579
|
+
}
|
|
580
|
+
isConsumerList(source) {
|
|
581
|
+
return Array.isArray(source) && (source.length === 0 || source[0] instanceof KafkaConsumer);
|
|
582
|
+
}
|
|
583
|
+
subscriptions(consumers) {
|
|
584
|
+
if (consumers.length === 0) throw new Error(i18n.t("empty_consumers"));
|
|
585
|
+
const each = {};
|
|
586
|
+
let groupId;
|
|
587
|
+
for (const consumer of consumers) {
|
|
588
|
+
const handlers = consumer["collect"]();
|
|
589
|
+
if (handlers.length === 0) continue;
|
|
590
|
+
if (groupId === void 0) groupId = consumer.groupId;
|
|
591
|
+
else if (consumer.groupId !== groupId) throw new Error(i18n.t("mixed_group_id"));
|
|
592
|
+
for (const handler of handlers) {
|
|
593
|
+
const name = handler.topic.name;
|
|
594
|
+
if (Object.hasOwn(each, name)) throw new Error(i18n.t("duplicate_topic", { topic: name }));
|
|
595
|
+
each[name] = {
|
|
596
|
+
rule: handler.topic.rule,
|
|
597
|
+
route: compose([
|
|
598
|
+
...this.settings.mount,
|
|
599
|
+
...handler.middlewareList,
|
|
600
|
+
middleware.kafka((ctx, _) => handler.action(ctx))
|
|
601
|
+
])
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
return {
|
|
606
|
+
groupId: groupId ?? "",
|
|
607
|
+
each
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
async handleMessage(payload, each, consumer, groupId) {
|
|
611
|
+
const { topic, partition, message, heartbeat } = payload;
|
|
612
|
+
const handler = each[topic];
|
|
613
|
+
if (!handler) throw new Error(i18n.t("unknown_topic", { topic }));
|
|
614
|
+
if (message.value == null) throw new Error(i18n.t("empty_message"));
|
|
615
|
+
const headers = "headers" in message ? message.headers : void 0;
|
|
616
|
+
this.assertIncomingSize(message.value, message.key, headers);
|
|
617
|
+
const ctx = {
|
|
618
|
+
value: await validate(this.decodeValue(message.value), handler.rule),
|
|
619
|
+
logger: this.settings.logger,
|
|
620
|
+
recordKey: this.recordKey(groupId, topic, partition, message.offset),
|
|
621
|
+
meta: {
|
|
622
|
+
topic,
|
|
623
|
+
partitionId: partition,
|
|
624
|
+
offset: message.offset,
|
|
625
|
+
timestamp: message.timestamp,
|
|
626
|
+
partitionKey: this.readPartitionKey(message.key),
|
|
627
|
+
headers: this.readHeaders(headers)
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
const pulse = this.startHeartbeat(heartbeat);
|
|
631
|
+
try {
|
|
632
|
+
await handler.route(ctx);
|
|
633
|
+
const failure = pulse.failure();
|
|
634
|
+
if (failure) throw failure;
|
|
635
|
+
if (this.consumeAborted) return;
|
|
636
|
+
await consumer.commitOffsets([{
|
|
637
|
+
topic,
|
|
638
|
+
partition,
|
|
639
|
+
offset: this.nextOffset(message.offset)
|
|
640
|
+
}]);
|
|
641
|
+
} finally {
|
|
642
|
+
pulse.stop();
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
assertIncomingSize(value, key, headers) {
|
|
646
|
+
let size = value.byteLength;
|
|
647
|
+
if (key) size += key.byteLength;
|
|
648
|
+
if (headers) for (const [name, raw] of Object.entries(headers)) {
|
|
649
|
+
size += Buffer.byteLength(name);
|
|
650
|
+
const values = Array.isArray(raw) ? raw : raw == null ? [] : [raw];
|
|
651
|
+
for (const item of values) size += typeof item === "string" ? Buffer.byteLength(item) : item.byteLength;
|
|
652
|
+
}
|
|
653
|
+
this.assertSize(size);
|
|
654
|
+
}
|
|
655
|
+
/** `groupId` 与主题按 URL 编码,避免其中的 `:` 打断分段。 */
|
|
656
|
+
recordKey(groupId, topic, partition, offset) {
|
|
657
|
+
return [
|
|
658
|
+
encodeURIComponent(groupId),
|
|
659
|
+
encodeURIComponent(topic),
|
|
660
|
+
String(partition),
|
|
661
|
+
encodeURIComponent(offset)
|
|
662
|
+
].join(":");
|
|
663
|
+
}
|
|
664
|
+
readPartitionKey(key) {
|
|
665
|
+
if (key == null) return null;
|
|
666
|
+
return key.toString("utf8");
|
|
667
|
+
}
|
|
668
|
+
readHeaders(headers) {
|
|
669
|
+
if (!headers) return {};
|
|
670
|
+
const result = {};
|
|
671
|
+
for (const [key, raw] of Object.entries(headers)) {
|
|
672
|
+
if (raw == null) continue;
|
|
673
|
+
const picked = Array.isArray(raw) ? raw[raw.length - 1] : raw;
|
|
674
|
+
if (picked == null) continue;
|
|
675
|
+
result[key] = typeof picked === "string" ? picked : picked.toString("utf8");
|
|
676
|
+
}
|
|
677
|
+
return result;
|
|
678
|
+
}
|
|
679
|
+
nextOffset(offset) {
|
|
680
|
+
if (!/^\d+$/.test(offset)) throw new Error(i18n.t("invalid_offset", { offset }));
|
|
681
|
+
return (BigInt(offset) + 1n).toString();
|
|
682
|
+
}
|
|
683
|
+
startHeartbeat(heartbeat) {
|
|
684
|
+
if (!(this.settings.heartbeatInterval > 0)) return {
|
|
685
|
+
stop() {},
|
|
686
|
+
failure: () => void 0
|
|
687
|
+
};
|
|
688
|
+
let failure;
|
|
689
|
+
const timer = setInterval(() => {
|
|
690
|
+
heartbeat().catch((error) => {
|
|
691
|
+
failure ??= error;
|
|
692
|
+
});
|
|
693
|
+
}, this.settings.heartbeatInterval);
|
|
694
|
+
return {
|
|
695
|
+
stop: () => clearInterval(timer),
|
|
696
|
+
failure: () => failure
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
// src/core/topic.ts
|
|
701
|
+
/** Kafka 主题名最大长度。 */
|
|
702
|
+
const TOPIC_NAME_MAX = 249;
|
|
703
|
+
/** 字母、数字、`.`、`_`、`-`。 */
|
|
704
|
+
const TOPIC_NAME_RE = /^[a-zA-Z0-9._-]+$/;
|
|
705
|
+
/**
|
|
706
|
+
* 一份主题契约:名字和校验规则。生产和消费都引用它。
|
|
707
|
+
* 请用 {@link defineKafkaTopic} 创建;构造函数为 `protected`,禁止业务侧直接 `new`。
|
|
708
|
+
* 建议放在 `src/topics/`,文件名以 `.topic.ts` 结尾,变量名以 `Topic` 结尾,
|
|
709
|
+
* 如 `order-created.topic.ts` 里的 `orderCreatedTopic`。
|
|
710
|
+
*/
|
|
711
|
+
var KafkaTopic = class KafkaTopic {
|
|
712
|
+
name;
|
|
713
|
+
rule;
|
|
714
|
+
constructor(name, rule) {
|
|
715
|
+
KafkaTopic.assertName(name);
|
|
716
|
+
this.name = name;
|
|
717
|
+
this.rule = rule;
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* 供 {@link defineKafkaTopic} 调用;带「消息体须可 JSON 还原」的类型门禁。
|
|
721
|
+
*/
|
|
722
|
+
static create(name, rule) {
|
|
723
|
+
return new KafkaTopic(name, rule);
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* 主题名须非空、不超过 249 字符,且只含字母、数字、`.`、`_`、`-`。
|
|
727
|
+
* 不能是 `.` 或 `..`。
|
|
728
|
+
*/
|
|
729
|
+
static assertName(name) {
|
|
730
|
+
if (name.length === 0) throw new Error(i18n.t("empty_topic"));
|
|
731
|
+
if (name.length > TOPIC_NAME_MAX) throw new Error(i18n.t("topic_name_too_long", {
|
|
732
|
+
length: String(name.length),
|
|
733
|
+
max: String(TOPIC_NAME_MAX)
|
|
734
|
+
}));
|
|
735
|
+
if (name === "." || name === ".." || !TOPIC_NAME_RE.test(name)) throw new Error(i18n.t("invalid_topic_name", { topic: name }));
|
|
736
|
+
}
|
|
737
|
+
};
|
|
738
|
+
/**
|
|
739
|
+
* 声明一个主题。建议每个主题一个文件,放在 `src/topics/`,文件名以 `.topic.ts` 结尾。
|
|
740
|
+
*
|
|
741
|
+
* ```ts
|
|
742
|
+
* // src/topics/order-created.topic.ts
|
|
743
|
+
* export const orderCreatedTopic = defineKafkaTopic('order.created', {
|
|
744
|
+
* orderId: rule.string(),
|
|
745
|
+
* amount: rule.number(),
|
|
746
|
+
* });
|
|
747
|
+
* ```
|
|
748
|
+
*/
|
|
749
|
+
function defineKafkaTopic(name, rule) {
|
|
750
|
+
return KafkaTopic["create"](name, rule);
|
|
751
|
+
}
|
|
752
|
+
export { KafkaConsumer, KafkaMiddleware, KafkaTopic, createKafkaService, defineKafkaTopic };
|
|
753
|
+
|
|
754
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/i18n/locales/zh-cn.ts","../src/i18n/locales/en-us.ts","../src/i18n/index.ts","../src/override/kafka-middleware.ts","../src/core/consumer.ts","../src/core/kafka.ts","../src/core/topic.ts"],"sourcesContent":["import { I18n } from '@aomex/common';\n\nexport const zh = I18n.define({\n empty_brokers: 'brokers 不能为空',\n empty_broker: 'brokers 含有空地址',\n empty_client_id: 'clientId 不能为空',\n empty_group_id: 'groupId 不能为空',\n empty_topic: '主题名不能为空',\n invalid_topic_name: '非法的主题名:{{topic}}',\n topic_name_too_long: '主题名过长:{{length}} > {{max}}',\n duplicate_topic: '主题重复登记:{{topic}}',\n mixed_group_id: '同一次消费只能有一个 groupId',\n empty_consumers: '没有找到 Kafka 消费者',\n already_consuming: '已有消费者在运行',\n closed: 'Kafka 连接已关闭',\n message_too_large: '消息大小超过限制:{{bytes}} > {{max}}',\n invalid_json: '消息不是合法的 JSON',\n empty_message: '消息体为空',\n encode_failed: '消息无法编码为 JSON',\n unknown_topic: '收到未订阅的主题:{{topic}}',\n invalid_offset: '非法的消息偏移量:{{offset}}',\n idempotent_requires_all_acks: '开启幂等生产者时 acks 必须为 -1',\n unsupported_sasl: '不支持的 SASL 机制:{{mechanism}}',\n unsupported_tls: 'TLS 配置无法交给客户端:{{name}}',\n heartbeat_exceeds_session: '心跳间隔必须小于会话超时',\n});\n","import { I18n } from '@aomex/common';\nimport { zh } from './zh-cn';\n\nexport const en = I18n.satisfies(zh).define({\n empty_brokers: 'brokers must not be empty',\n empty_broker: 'brokers contains an empty address',\n empty_client_id: 'clientId must not be empty',\n empty_group_id: 'groupId must not be empty',\n empty_topic: 'Topic name must not be empty',\n invalid_topic_name: 'Invalid topic name: {{topic}}',\n topic_name_too_long: 'Topic name is too long: {{length}} > {{max}}',\n duplicate_topic: 'Topic is registered more than once: {{topic}}',\n mixed_group_id: 'One consume call must use a single groupId',\n empty_consumers: 'No Kafka consumers were found',\n already_consuming: 'A consumer is already running',\n closed: 'Kafka connection is closed',\n message_too_large: 'Message exceeds the size limit: {{bytes}} > {{max}}',\n invalid_json: 'Message is not valid JSON',\n empty_message: 'Message payload is empty',\n encode_failed: 'Message could not be encoded as JSON',\n unknown_topic: 'Received an unsubscribed topic: {{topic}}',\n invalid_offset: 'Invalid message offset: {{offset}}',\n idempotent_requires_all_acks: 'acks must be -1 when the idempotent producer is enabled',\n unsupported_sasl: 'Unsupported SASL mechanism: {{mechanism}}',\n unsupported_tls: 'TLS option cannot be passed to the client: {{name}}',\n heartbeat_exceeds_session: 'Heartbeat interval must be less than the session timeout',\n});\n","import { createI18n } from '@aomex/common';\nimport { zh } from './locales/zh-cn';\nimport { en } from './locales/en-us';\n\nexport const i18n = createI18n({\n zh,\n en,\n load: (file) => import(new URL(`./locales/${file}.js`, import.meta.url).href),\n});\n","import { Middleware, MixinMiddleware, type Next } from '@aomex/common';\nimport type { NonReadonly } from '@aomex/internal-tools';\nimport type { Kafka } from '../core/kafka';\n\nexport type KafkaMiddlewareToken<P extends object = object> =\n KafkaMiddleware<P> | MixinMiddleware<P>;\n\ndeclare module '@aomex/common' {\n export interface MiddlewarePlatform<Deps extends object = object> {\n readonly kafka: <Props extends object = object>(\n fn:\n | KafkaMiddlewareArguments<Middleware.MergeDeps<Props, Deps>>['fn']\n | KafkaMiddlewareArguments<Middleware.MergeDeps<Props, Deps>>,\n ) => object extends Deps\n ? KafkaMiddleware<Props>\n : KafkaMiddleware<Props> & {\n _contextType: Middleware.WithDeps<Kafka.Context, Deps>;\n };\n }\n}\n\ninterface KafkaMiddlewareArguments<T extends object> {\n fn: (ctx: NonReadonly<T> & Kafka.Context, next: Next) => any;\n}\n\n/**\n * Kafka 消费专用中间件;`KafkaConsumer` / `createKafkaService` 的 `mount` 仅允许本类或 `mixin`。\n */\nexport class KafkaMiddleware<Props extends object = object> extends Middleware<Props> {\n declare public _contextType: Kafka.Context;\n declare protected _kafka_middleware_: 'kafka-middleware';\n\n constructor(\n args: KafkaMiddlewareArguments<Props>['fn'] | KafkaMiddlewareArguments<Props>,\n ) {\n const { fn } =\n typeof args === 'function'\n ? ({ fn: args } satisfies KafkaMiddlewareArguments<Props>)\n : args;\n super(fn);\n }\n}\n\nMiddleware.register('kafka', KafkaMiddleware);\n","import { Middleware } from '@aomex/common';\nimport type { Union2Intersection } from '@aomex/internal-tools';\nimport { i18n } from '../i18n';\nimport type { Kafka } from './kafka';\nimport type { KafkaTopic } from './topic';\nimport type { KafkaMiddlewareToken } from '../override';\nimport '../override/kafka-middleware.js';\n\ntype KafkaHandler = {\n topic: KafkaTopic<unknown>;\n middlewareList: KafkaMiddlewareToken[];\n action: (ctx: Kafka.Context<unknown>) => void | Promise<void>;\n};\n\nexport interface KafkaConsumerOptions<T extends KafkaMiddlewareToken[] | [] = []> {\n /**\n * 消费组 ID。同组消费者共同分摊分区;同一次 `consume` 合并的多个实例必须相同。\n */\n groupId: string;\n /**\n * 本消费组下所有主题共用的中间件(先于主题级 `mount` 执行)。\n * 仅 `middleware.kafka` / `middleware.mixin`。\n */\n mount?: T;\n}\n\nexport interface KafkaHandlerOptions<\n Value,\n Props extends object | unknown,\n T extends KafkaMiddlewareToken[] | [],\n> {\n /**\n * 为 `true` 时不登记该主题(便于按环境开关)。\n */\n disabled?: boolean;\n /**\n * 仅本主题的中间件。仅 `middleware.kafka` / `middleware.mixin`。\n */\n mount?: T;\n /**\n * 消费处理函数;`ctx` 类型会合并消费组 / 主题级 `mount` 的 Props,并始终带 `logger`。\n */\n action: (ctx: KafkaConsumer.Context<Value, Props, T>) => void | Promise<void>;\n}\n\nexport declare namespace KafkaConsumer {\n export type Interface<\n Props extends object | unknown,\n T extends KafkaMiddlewareToken[] | [],\n > = T extends []\n ? Props\n : Props & Union2Intersection<Middleware.CollectArrayType<T[number]>>;\n\n export type Context<\n Value,\n Props extends object | unknown,\n T extends KafkaMiddlewareToken[] | [],\n > = Kafka.Context<Value> & Interface<Props, T>;\n}\n\n/**\n * 一个消费组上的主题登记,用法对齐路由:先 `new`,再 `on`。\n * 建议放在 `src/consumers/`,主题从 `src/topics/*.topic.ts` 引入。\n * 同一目录里的多个实例交给 `consume` 合并,且必须是同一个 `groupId`。\n */\nexport class KafkaConsumer<\n T extends KafkaMiddlewareToken[] | [] = [],\n Props extends object | unknown = Kafka.Props &\n (T extends [] ? object : Union2Intersection<Middleware.CollectArrayType<T[number]>>),\n> {\n readonly groupId: string;\n private readonly middlewareList: KafkaMiddlewareToken[];\n private readonly handlers: KafkaHandler[] = [];\n\n constructor(options: KafkaConsumerOptions<T>) {\n if (options.groupId.length === 0) {\n throw new Error(i18n.t('empty_group_id'));\n }\n this.groupId = options.groupId;\n this.middlewareList = options.mount || [];\n }\n\n /**\n * 登记一个主题。`action` 收到 `ctx`,其中 `value` 从该主题的规则推断。\n * 同一个实例里主题名不能重复。\n * `disabled: true` 时不登记。\n */\n public on<V, M extends KafkaMiddlewareToken[] | [] = []>(\n topic: KafkaTopic<V>,\n options: KafkaHandlerOptions<V, Props, M>,\n ): void {\n if (options.disabled === true) return;\n if (this.handlers.some((item) => item.topic.name === topic.name)) {\n throw new Error(i18n.t('duplicate_topic', { topic: topic.name }));\n }\n this.handlers.push({\n topic: topic as KafkaTopic<unknown>,\n middlewareList: [\n ...this.middlewareList,\n ...((options.mount || []) as KafkaMiddlewareToken[]),\n ],\n action: options.action as KafkaHandler['action'],\n });\n }\n\n protected collect(): readonly KafkaHandler[] {\n return this.handlers;\n }\n}\n","import {\n compose,\n middleware,\n parseDuration,\n Service,\n validate,\n type ComposeFn,\n type DurationInput,\n type ValidatorToken,\n} from '@aomex/common';\nimport {\n getFileValues,\n pathToFiles,\n type GlobPathOptions,\n} from '@aomex/internal-file-import';\nimport type { Logger } from '@aomex/logger';\nimport { KafkaJS } from '@confluentinc/kafka-javascript';\nimport type { ConnectionOptions } from 'node:tls';\nimport { KafkaConsumer } from './consumer';\nimport { i18n } from '../i18n';\nimport type { KafkaMiddlewareToken } from '../override';\nimport type { KafkaTopic } from './topic';\nimport '../override/kafka-middleware.js';\n\ntype Consumption = {\n resolve: () => void;\n reject: (error: unknown) => void;\n settled: boolean;\n};\n\ntype WireMessage = {\n value: Buffer;\n key?: string;\n headers?: Record<string, string>;\n partition?: number;\n};\n\ntype RecordMetadata = KafkaJS.RecordMetadata;\n\ntype ConsumerEvents = {\n CRASH: string;\n STOP: string;\n};\n\ntype CrashListener = (event: { payload: { restart?: boolean; error?: unknown } }) => void;\n\ntype KafkaConsumerClient = KafkaJS.Consumer & {\n events?: ConsumerEvents;\n on?(event: string, listener: CrashListener): () => void;\n};\n\ntype BoundHandler = {\n rule: ValidatorToken;\n route: ComposeFn;\n};\n\ntype Subscription = {\n groupId: string;\n each: Record<string, BoundHandler>;\n};\n\ntype Resolved = {\n brokers: readonly string[];\n clientId: string;\n logger: Logger;\n mount: readonly KafkaMiddlewareToken[];\n ssl?: Kafka.Ssl;\n sasl?: Kafka.Sasl;\n connectionTimeout?: number;\n requestTimeout?: number;\n allowAutoTopicCreation: boolean;\n idempotent: boolean;\n acks: -1 | 0 | 1;\n maxMessageBytes: number;\n sessionTimeout: number;\n heartbeatInterval: number;\n encode?: (value: unknown) => Buffer;\n decode?: (buffer: Buffer) => unknown;\n};\n\n/** 解析成毫秒。客户端只接受整数。 */\nfunction durationMs(value: DurationInput): number {\n return Math.round(parseDuration(value));\n}\n\n/** 配置在工厂里校验一次。`combineServices` 只能 `new Ctor()`,所以结果是零参类。 */\nfunction resolveOptions(options: Kafka.Options<KafkaMiddlewareToken[] | []>): Resolved {\n if (options.brokers.length === 0) {\n throw new Error(i18n.t('empty_brokers'));\n }\n const brokers: string[] = [];\n for (const broker of options.brokers) {\n if (broker.length === 0) {\n throw new Error(i18n.t('empty_broker'));\n }\n brokers.push(broker);\n }\n const idempotent = options.idempotent ?? true;\n const acks = options.acks ?? -1;\n if (idempotent && acks !== -1) {\n throw new Error(i18n.t('idempotent_requires_all_acks'));\n }\n const sessionTimeout = durationMs(options.sessionTimeout ?? '30s');\n const heartbeatInterval =\n options.heartbeatInterval === undefined\n ? Math.min(durationMs('3s'), Math.max(1, Math.floor(sessionTimeout / 3)))\n : durationMs(options.heartbeatInterval);\n if (heartbeatInterval > 0 && heartbeatInterval >= sessionTimeout) {\n throw new Error(i18n.t('heartbeat_exceeds_session'));\n }\n if (options.clientId.length === 0) {\n throw new Error(i18n.t('empty_client_id'));\n }\n return {\n brokers,\n clientId: options.clientId,\n logger: options.logger,\n mount: options.mount ?? [],\n ...(options.ssl === undefined ? {} : { ssl: options.ssl }),\n ...(options.sasl === undefined ? {} : { sasl: options.sasl }),\n ...(options.connectionTimeout === undefined\n ? {}\n : { connectionTimeout: durationMs(options.connectionTimeout) }),\n ...(options.requestTimeout === undefined\n ? {}\n : { requestTimeout: durationMs(options.requestTimeout) }),\n allowAutoTopicCreation: options.allowAutoTopicCreation ?? false,\n idempotent,\n acks,\n maxMessageBytes: options.maxMessageBytes ?? 1_048_576,\n sessionTimeout,\n heartbeatInterval,\n ...(options.encode === undefined\n ? {}\n : { encode: options.encode as (value: unknown) => Buffer }),\n ...(options.decode === undefined ? {} : { decode: options.decode }),\n };\n}\n\n/**\n * 创建 Kafka 服务类,交给 `combineServices`。\n *\n * 同一个类同时给 Web 与 Console 用:Web 里 `produce`,Console 指令里 `consume`。\n * 生产者在首次生产时连接,消费者在 `consume` 时连接,只发消息的进程不会加入消费组。\n * 处理成功后提交下一条偏移量(至少一次)。处理函数抛错则不提交,并结束本次消费。\n * 消费在 JSON 解析后按主题上的规则校验,失败同样不提交。\n * WebApp / ConsoleApp 关停时调用 `onDestroy` 断开连接。\n *\n * 消息体必须是 JSON。Date、bigint、Buffer 等无法原样还原的规则会在类型上被拒绝。\n * 需要别的编码时,传入 `encode` / `decode`。\n *\n * ```ts\n * // src/topics/order-created.topic.ts\n * export const orderCreatedTopic = defineKafkaTopic('order.created', {\n * orderId: rule.string(),\n * amount: rule.number(),\n * });\n *\n * // src/consumers/order-created.consumer.ts\n * import { orderCreatedTopic } from '../topics/order-created.topic.js';\n * export const consumer = new KafkaConsumer({ groupId: 'billing' });\n * consumer.on(orderCreatedTopic, {\n * action: async (ctx) => {\n * ctx.value.orderId;\n * ctx.logger.info(ctx.recordKey);\n * },\n * });\n *\n * // src/services/kafka.service.ts\n * export const KafkaService = createKafkaService({\n * brokers: ['127.0.0.1:9092'],\n * clientId: 'shop',\n * logger,\n * });\n *\n * // src/routers/order.router.ts\n * await services.kafka.produce({\n * topic: orderCreatedTopic,\n * value: { orderId: '1', amount: 20 },\n * });\n * await services.kafka.consume('./src/consumers');\n * ```\n */\nexport function createKafkaService<T extends KafkaMiddlewareToken[] | [] = []>(\n options: Kafka.Options<T>,\n): new () => Service & Kafka.Service {\n const settings = resolveOptions(options);\n return class KafkaService extends KafkaRuntime {\n public constructor() {\n super(settings);\n }\n };\n}\n\nclass KafkaRuntime extends Service {\n private readonly settings: Resolved;\n private client?: KafkaJS.Kafka;\n private producer?: KafkaJS.Producer;\n private producerReady?: Promise<KafkaJS.Producer>;\n private consumer?: KafkaConsumerClient;\n private releaseTask?: Promise<void>;\n private consumption?: Consumption;\n private unbind: Array<() => void> = [];\n private consuming = false;\n private stopRequested = false;\n /** 消费已失败:拦住并发 eachMessage 继续处理或提交。 */\n private consumeAborted = false;\n private closed = false;\n\n protected constructor(settings: Resolved) {\n super();\n this.settings = settings;\n }\n\n /**\n * 生产一条消息。返回 broker 回执;`acks` 为 `0` 时数组为空。\n */\n public async produce<T>(\n message: {\n topic: KafkaTopic<T>;\n value: NoInfer<T>;\n } & Kafka.SendOptions,\n ): Promise<readonly Kafka.Receipt[]> {\n this.assertOpen();\n const wire = this.toMessage(message.value, message);\n const producer = await this.ensureProducer();\n const metadata = await producer.send({\n topic: message.topic.name,\n messages: [wire],\n });\n return this.toReceipts(metadata);\n }\n\n /**\n * 一次生产多条消息,按主题分组提交。空数组直接返回。\n * 回执顺序与 broker 响应一致,不保证与入参下标对齐。\n * 单条形状与 `produce` 相同。\n */\n public async produceMany<const T extends readonly unknown[]>(messages: {\n [I in keyof T]: {\n topic: KafkaTopic<T[I]>;\n value: NoInfer<T[I]>;\n } & Kafka.SendOptions;\n }): Promise<readonly Kafka.Receipt[]> {\n this.assertOpen();\n if (messages.length === 0) return [];\n\n const grouped = new Map<string, WireMessage[]>();\n for (const item of messages) {\n const wire = this.toMessage(item.value, item);\n const list = grouped.get(item.topic.name);\n if (list) list.push(wire);\n else grouped.set(item.topic.name, [wire]);\n }\n\n const producer = await this.ensureProducer();\n const metadata = await producer.sendBatch({\n topicMessages: [...grouped.entries()].map(([topic, batch]) => ({\n topic,\n messages: batch,\n })),\n });\n return this.toReceipts(metadata);\n }\n\n /**\n * 加入消费组并持续处理消息,直到进程关停或处理失败。\n *\n * 在 Console 指令里调用。不要放进 HTTP 请求:Promise 在关停前不会完成。\n * 处理函数成功返回后才提交下一条偏移量。抛错则不提交,Promise 拒绝,进程应按失败退出。\n * 同一实例不能并行消费;两个消费组请再 `createKafkaService` 一次。\n */\n public async consume(\n source: Kafka.ConsumeSource,\n options?: Kafka.ConsumeOptions,\n ): Promise<void> {\n this.assertOpen();\n if (this.consuming) {\n throw new Error(i18n.t('already_consuming'));\n }\n this.consuming = true;\n this.stopRequested = false;\n this.consumeAborted = false;\n let input: Subscription;\n let consumer: KafkaConsumerClient;\n const heartbeatInterval = this.settings.heartbeatInterval;\n try {\n input = this.subscriptions(await this.loadConsumers(source));\n if (Object.keys(input.each).length === 0) {\n this.consuming = false;\n return;\n }\n consumer = this.createClient().consumer({\n kafkaJS: {\n groupId: input.groupId,\n allowAutoTopicCreation: this.settings.allowAutoTopicCreation,\n sessionTimeout: this.settings.sessionTimeout,\n ...(heartbeatInterval > 0 ? { heartbeatInterval } : {}),\n fromBeginning: options?.fromBeginning ?? false,\n autoCommit: false,\n ...this.consumerFetch(),\n },\n });\n } catch (error) {\n this.consuming = false;\n throw error;\n }\n this.consumer = consumer;\n this.bindConsumer(consumer);\n const done = this.beginConsumption();\n\n try {\n await consumer.connect();\n await consumer.subscribe({ topics: Object.keys(input.each) });\n await consumer.run({\n eachMessage: async (payload) => {\n // 客户端在 eachMessage 抛错后仍可能继续调度;门闩拦住后续处理。\n if (this.consumeAborted) return;\n try {\n await this.handleMessage(payload, input.each, consumer, input.groupId);\n } catch (error) {\n this.abortConsumption(error);\n throw error;\n }\n },\n });\n await done;\n } finally {\n await this.releaseConsumer();\n this.clearBindings();\n this.finishConsumption();\n this.consumption = undefined;\n this.consuming = false;\n }\n }\n\n /** 创建客户端。网络连接推迟到发送或消费。 */\n protected override async onInit(): Promise<void> {\n this.createClient();\n }\n\n /** 停止消费者并断开生产者。重复调用无效果。 */\n protected override async onDestroy(): Promise<void> {\n if (this.closed) return;\n this.closed = true;\n await this.releaseConsumer();\n await this.releaseProducer();\n }\n\n private createClient(): KafkaJS.Kafka {\n if (this.client) return this.client;\n this.assertOpen();\n const { clientId, brokers, ssl, sasl, connectionTimeout, requestTimeout } =\n this.settings;\n const config: KafkaJS.CommonConstructorConfig = {\n 'message.max.bytes': this.wireMessageMaxBytes(),\n 'kafkaJS': {\n clientId,\n brokers: [...brokers],\n logLevel: KafkaJS.logLevel.WARN,\n logger: this.toClientLogger(),\n ...(ssl === undefined ? {} : { ssl: ssl !== false }),\n ...(sasl === undefined ? {} : { sasl: this.toSasl(sasl) }),\n ...(connectionTimeout === undefined ? {} : { connectionTimeout }),\n ...(requestTimeout === undefined ? {} : { requestTimeout }),\n },\n };\n this.applyTls(config);\n this.client = new KafkaJS.Kafka(config);\n return this.client;\n }\n\n /**\n * 把应用 `logger` 适配成客户端 logger。\n * 默认 `WARN`;只转发文案,不带 `extra`(可能含连接细节)。\n */\n private toClientLogger(): KafkaJS.Logger {\n const app = this.settings.logger;\n let current = KafkaJS.logLevel.WARN;\n const logger: KafkaJS.Logger = {\n setLogLevel: (next) => {\n current = next;\n },\n namespace: () => logger,\n info: (message) => {\n if (current >= KafkaJS.logLevel.INFO) app.info(message);\n },\n warn: (message) => {\n if (current >= KafkaJS.logLevel.WARN) app.warn(message);\n },\n error: (message) => {\n if (current >= KafkaJS.logLevel.ERROR) app.error(message);\n },\n debug: (message) => {\n if (current >= KafkaJS.logLevel.DEBUG) app.debug(message);\n },\n };\n return logger;\n }\n\n /** 把 TLS 对象映射成客户端认识的证书项。布尔值只表示开关。 */\n private applyTls(config: KafkaJS.CommonConstructorConfig): void {\n const ssl = this.settings.ssl;\n if (ssl == null || typeof ssl !== 'object') return;\n if (ssl.rejectUnauthorized === false) {\n config['enable.ssl.certificate.verification'] = false;\n }\n const ca = this.pem(ssl.ca, 'ca');\n if (ca !== undefined) config['ssl.ca.pem'] = ca;\n const cert = this.pem(ssl.cert, 'cert');\n if (cert !== undefined) config['ssl.certificate.pem'] = cert;\n const key = this.pem(ssl.key, 'key');\n if (key !== undefined) config['ssl.key.pem'] = key;\n if (typeof ssl.passphrase === 'string') config['ssl.key.password'] = ssl.passphrase;\n }\n\n private pem(value: unknown, name: string): string | undefined {\n if (value == null) return undefined;\n if (typeof value === 'string') return value;\n if (Buffer.isBuffer(value)) return value.toString('utf8');\n if (Array.isArray(value)) {\n return value.map((item) => this.pem(item, name) ?? '').join('\\n');\n }\n throw new Error(i18n.t('unsupported_tls', { name }));\n }\n\n private toSasl(sasl: Kafka.Sasl): KafkaJS.SASLOptions {\n if (sasl.mechanism === 'aws') {\n throw new Error(i18n.t('unsupported_sasl', { mechanism: 'aws' }));\n }\n if (sasl.mechanism === 'oauthbearer') {\n const provide = sasl.oauthBearerProvider;\n return {\n mechanism: 'oauthbearer',\n oauthBearerProvider: async () => {\n const token = await provide();\n return {\n value: token.value,\n principal: '',\n lifetime: Date.now() + 3_600_000,\n };\n },\n };\n }\n return sasl;\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(i18n.t('closed'));\n }\n }\n\n private async ensureProducer(): Promise<KafkaJS.Producer> {\n this.assertOpen();\n this.producerReady ??= this.connectProducer().catch((error) => {\n this.producerReady = undefined;\n throw error;\n });\n return this.producerReady;\n }\n\n /**\n * 幂等开启时补上客户端兼容层不会自动改写的参数:在途请求 5、重试 `(2 ** 31) - 1`、先进先出。\n * 每次生产都等待回执,不等待攒批。\n */\n private producerConfig(): KafkaJS.ProducerConstructorConfig {\n const kafkaJS: KafkaJS.ProducerConfig = {\n idempotent: this.settings.idempotent,\n allowAutoTopicCreation: this.settings.allowAutoTopicCreation,\n acks: this.settings.acks,\n };\n const config: KafkaJS.ProducerConstructorConfig = {\n kafkaJS,\n 'linger.ms': 0,\n };\n if (!this.settings.idempotent) return config;\n kafkaJS.maxInFlightRequests = 5;\n kafkaJS.retry = { retries: 2 ** 31 - 1 };\n config['queuing.strategy'] = 'fifo';\n return config;\n }\n\n /** 协议报文上限。客户端只接受 1000 到 1000000000。 */\n private wireMessageMaxBytes(): number {\n const bytes = this.settings.maxMessageBytes;\n if (bytes < 1_000) return 1_000;\n if (bytes > 1_000_000_000) return 1_000_000_000;\n return bytes;\n }\n\n /** 拉取上限只在允许的报文更大时上调。 */\n private consumerFetch(): { maxBytesPerPartition?: number; maxBytes?: number } {\n const bytes = this.wireMessageMaxBytes();\n return {\n ...(bytes > 1_048_576 ? { maxBytesPerPartition: bytes } : {}),\n ...(bytes > 10_485_760 ? { maxBytes: bytes } : {}),\n };\n }\n\n private async connectProducer(): Promise<KafkaJS.Producer> {\n const producer = this.createClient().producer(this.producerConfig());\n this.producer = producer;\n try {\n await producer.connect();\n } catch (error) {\n this.producer = undefined;\n await producer.disconnect().catch(() => undefined);\n throw error;\n }\n if (this.closed) {\n throw new Error(i18n.t('closed'));\n }\n return producer;\n }\n\n private async releaseProducer(): Promise<void> {\n const producer = this.producer;\n this.producer = undefined;\n this.producerReady = undefined;\n if (!producer) return;\n await producer.disconnect();\n }\n\n private toMessage(value: unknown, options?: Kafka.SendOptions): WireMessage {\n const encoded = this.encodeValue(value);\n let size = encoded.byteLength;\n if (options?.partitionKey !== undefined) {\n size += Buffer.byteLength(options.partitionKey);\n }\n if (options?.headers) {\n for (const [name, header] of Object.entries(options.headers)) {\n size += Buffer.byteLength(name) + Buffer.byteLength(header);\n }\n }\n this.assertSize(size);\n return {\n value: encoded,\n // 客户端消息字段仍叫 key\n ...(options?.partitionKey === undefined ? {} : { key: options.partitionKey }),\n ...(options?.headers === undefined ? {} : { headers: options.headers }),\n // 客户端消息字段仍叫 partition\n ...(options?.partitionId === undefined ? {} : { partition: options.partitionId }),\n };\n }\n\n /** 默认 JSON。`encode` 的返回值仍受 `maxMessageBytes` 约束。 */\n private encodeValue(value: unknown): Buffer {\n const encode = this.settings.encode;\n if (encode) return encode(value);\n let json: string | undefined;\n try {\n json = JSON.stringify(value) as string | undefined;\n } catch (error) {\n throw new Error(i18n.t('encode_failed'), { cause: error });\n }\n if (typeof json !== 'string') {\n throw new Error(i18n.t('encode_failed'));\n }\n return Buffer.from(json);\n }\n\n /** 默认 JSON。解析失败抛出固定文案。 */\n private decodeValue(buffer: Buffer): unknown {\n const decode = this.settings.decode;\n if (decode) return decode(buffer);\n try {\n return JSON.parse(buffer.toString('utf8')) as unknown;\n } catch (error) {\n throw new Error(i18n.t('invalid_json'), { cause: error });\n }\n }\n\n private assertSize(bytes: number): void {\n if (bytes > this.settings.maxMessageBytes) {\n throw new Error(\n i18n.t('message_too_large', {\n bytes: String(bytes),\n max: String(this.settings.maxMessageBytes),\n }),\n );\n }\n }\n\n private toReceipts(metadata: RecordMetadata[]): Kafka.Receipt[] {\n return metadata.map((item) => ({\n topic: item.topicName,\n partitionId: item.partition,\n offset: item.offset ?? item.baseOffset ?? null,\n }));\n }\n\n private beginConsumption(): Promise<void> {\n const { promise, resolve, reject } = Promise.withResolvers<void>();\n this.consumption = { resolve, reject, settled: false };\n return promise;\n }\n\n private finishConsumption(): void {\n const current = this.consumption;\n if (!current || current.settled) return;\n current.settled = true;\n current.resolve();\n }\n\n private failConsumption(error: unknown): void {\n const current = this.consumption;\n if (!current || current.settled) return;\n current.settled = true;\n current.reject(error);\n }\n\n /** 标记消费失败、拒绝 `consume` Promise,并尽快断开,避免客户端继续拉取。 */\n private abortConsumption(error: unknown): void {\n this.consumeAborted = true;\n this.failConsumption(error);\n void this.releaseConsumer();\n }\n\n private bindConsumer(consumer: KafkaConsumerClient): void {\n const events = consumer.events;\n if (events == null || typeof consumer.on !== 'function') return;\n const listen = consumer.on.bind(consumer);\n this.unbind.push(\n listen(events.CRASH, (event) => {\n if (event.payload.restart) return;\n this.abortConsumption(event.payload.error);\n }),\n listen(events.STOP, () => {\n if (!this.stopRequested) return;\n this.finishConsumption();\n }),\n );\n }\n\n private clearBindings(): void {\n for (const off of this.unbind) off();\n this.unbind = [];\n }\n\n private releaseConsumer(): Promise<void> {\n if (this.releaseTask) return this.releaseTask;\n const consumer = this.consumer;\n const ending = this.consumption;\n this.consumer = undefined;\n this.stopRequested = true;\n this.releaseTask = (consumer ? consumer.disconnect() : Promise.resolve()).finally(\n () => {\n // 客户端的 run() 立刻返回,且没有 STOP 事件。断开后结束「发起本次释放」时的那轮 consume。\n if (ending && !ending.settled) {\n ending.settled = true;\n ending.resolve();\n }\n this.releaseTask = undefined;\n },\n );\n return this.releaseTask;\n }\n\n private async loadConsumers(source: Kafka.ConsumeSource): Promise<KafkaConsumer[]> {\n if (source instanceof KafkaConsumer) return [source];\n if (this.isConsumerList(source)) return [...source];\n const files = await pathToFiles(source);\n return getFileValues(files, (item) => item instanceof KafkaConsumer);\n }\n\n private isConsumerList(\n source: Kafka.ConsumeSource,\n ): source is readonly KafkaConsumer[] {\n return (\n Array.isArray(source) && (source.length === 0 || source[0] instanceof KafkaConsumer)\n );\n }\n\n private subscriptions(consumers: readonly KafkaConsumer[]): Subscription {\n if (consumers.length === 0) {\n throw new Error(i18n.t('empty_consumers'));\n }\n const each: Record<string, BoundHandler> = {};\n let groupId: string | undefined;\n for (const consumer of consumers) {\n const handlers = consumer['collect']();\n if (handlers.length === 0) continue;\n if (groupId === undefined) groupId = consumer.groupId;\n else if (consumer.groupId !== groupId) {\n throw new Error(i18n.t('mixed_group_id'));\n }\n for (const handler of handlers) {\n const name = handler.topic.name;\n if (Object.hasOwn(each, name)) {\n throw new Error(i18n.t('duplicate_topic', { topic: name }));\n }\n each[name] = {\n rule: handler.topic.rule,\n route: compose([\n ...this.settings.mount,\n ...handler.middlewareList,\n middleware.kafka((ctx, _) => handler.action(ctx)),\n ]),\n };\n }\n }\n return { groupId: groupId ?? '', each };\n }\n\n private async handleMessage(\n payload: KafkaJS.EachMessagePayload,\n each: Readonly<Record<string, BoundHandler>>,\n consumer: KafkaConsumerClient,\n groupId: string,\n ): Promise<void> {\n const { topic, partition, message, heartbeat } = payload;\n const handler = each[topic];\n if (!handler) {\n throw new Error(i18n.t('unknown_topic', { topic }));\n }\n if (message.value == null) {\n throw new Error(i18n.t('empty_message'));\n }\n\n const headers = 'headers' in message ? message.headers : undefined;\n this.assertIncomingSize(message.value, message.key, headers);\n const value = await validate(this.decodeValue(message.value), handler.rule);\n const ctx: Kafka.Context = {\n value,\n logger: this.settings.logger,\n recordKey: this.recordKey(groupId, topic, partition, message.offset),\n meta: {\n topic,\n partitionId: partition,\n offset: message.offset,\n timestamp: message.timestamp,\n partitionKey: this.readPartitionKey(message.key),\n headers: this.readHeaders(headers),\n },\n };\n const pulse = this.startHeartbeat(heartbeat);\n try {\n await handler.route(ctx);\n const failure = pulse.failure();\n if (failure) throw failure;\n // 并发分区上另一条消息可能已触发失败;提交前再拦一次。\n if (this.consumeAborted) return;\n await consumer.commitOffsets([\n { topic, partition, offset: this.nextOffset(message.offset) },\n ]);\n } finally {\n pulse.stop();\n }\n }\n\n private assertIncomingSize(\n value: Buffer,\n key: Buffer | null,\n headers: KafkaJS.IHeaders | undefined,\n ): void {\n let size = value.byteLength;\n if (key) size += key.byteLength;\n if (headers) {\n for (const [name, raw] of Object.entries(headers)) {\n size += Buffer.byteLength(name);\n const values = Array.isArray(raw) ? raw : raw == null ? [] : [raw];\n for (const item of values) {\n size += typeof item === 'string' ? Buffer.byteLength(item) : item.byteLength;\n }\n }\n }\n this.assertSize(size);\n }\n\n /** `groupId` 与主题按 URL 编码,避免其中的 `:` 打断分段。 */\n private recordKey(\n groupId: string,\n topic: string,\n partition: number,\n offset: string,\n ): string {\n return [\n encodeURIComponent(groupId),\n encodeURIComponent(topic),\n String(partition),\n encodeURIComponent(offset),\n ].join(':');\n }\n\n private readPartitionKey(key: Buffer | null): string | null {\n if (key == null) return null;\n return key.toString('utf8');\n }\n\n private readHeaders(headers: KafkaJS.IHeaders | undefined): Record<string, string> {\n if (!headers) return {};\n const result: Record<string, string> = {};\n for (const [key, raw] of Object.entries(headers)) {\n if (raw == null) continue;\n const picked = Array.isArray(raw) ? raw[raw.length - 1] : raw;\n if (picked == null) continue;\n result[key] = typeof picked === 'string' ? picked : picked.toString('utf8');\n }\n return result;\n }\n\n private nextOffset(offset: string): string {\n if (!/^\\d+$/.test(offset)) {\n throw new Error(i18n.t('invalid_offset', { offset }));\n }\n return (BigInt(offset) + 1n).toString();\n }\n\n private startHeartbeat(heartbeat: () => Promise<void>): {\n stop: () => void;\n failure: () => unknown;\n } {\n if (!(this.settings.heartbeatInterval > 0)) {\n return { stop() {}, failure: () => undefined };\n }\n let failure: unknown;\n const timer = setInterval(() => {\n void heartbeat().catch((error) => {\n failure ??= error;\n });\n }, this.settings.heartbeatInterval);\n return {\n stop: () => clearInterval(timer),\n failure: () => failure,\n };\n }\n}\n\nexport namespace Kafka {\n /** `createKafkaService` 返回的实例。配置与连接不在这个表面上。 */\n export interface Service {\n produce<T>(\n message: {\n topic: KafkaTopic<T>;\n value: NoInfer<T>;\n } & SendOptions,\n ): Promise<readonly Receipt[]>;\n\n produceMany<const T extends readonly unknown[]>(messages: {\n [I in keyof T]: {\n topic: KafkaTopic<T[I]>;\n value: NoInfer<T[I]>;\n } & SendOptions;\n }): Promise<readonly Receipt[]>;\n\n consume(source: ConsumeSource, options?: ConsumeOptions): Promise<void>;\n }\n\n export type ConsumeSource = KafkaConsumer | readonly KafkaConsumer[] | GlobPathOptions;\n\n export interface ConsumeOptions {\n /**\n * 为 `true` 时,在没有已提交位点时从最早偏移量读;默认 `false`(从最新)。\n * 已有提交位点时仍从提交处继续,不受本选项影响。\n */\n fromBeginning?: boolean;\n }\n\n export type Ssl = boolean | ConnectionOptions;\n\n export type Sasl =\n | { mechanism: 'plain'; username: string; password: string }\n | { mechanism: 'scram-sha-256'; username: string; password: string }\n | { mechanism: 'scram-sha-512'; username: string; password: string }\n | {\n mechanism: 'aws';\n authorizationIdentity: string;\n accessKeyId: string;\n secretAccessKey: string;\n sessionToken?: string;\n }\n | {\n mechanism: 'oauthbearer';\n oauthBearerProvider: () => Promise<{ value: string }>;\n };\n\n /**\n * 模块扩充点,可挂服务级推断类型:\n *\n * ```ts\n * declare module '@aomex/kafka' {\n * namespace Kafka {\n * interface Props {\n * traceId: string;\n * }\n * }\n * }\n * ```\n */\n export interface Props {}\n\n export interface Options<T extends KafkaMiddlewareToken[] | [] = []> {\n /** broker 地址,如 `127.0.0.1:9092`。 */\n brokers: readonly string[];\n\n /**\n * 应用日志。消费 `ctx.logger` 与此实例相同。\n * 客户端内部日志(默认 `WARN`)也会经适配器写入本实例,不转发 `extra`。\n */\n logger: Logger;\n\n /**\n * 本服务下所有消费共用的中间件(先于消费组 / 主题级 `mount` 执行)。\n * 仅 `middleware.kafka` / `middleware.mixin`。\n */\n mount?: T;\n\n /**\n * 客户端标识,任意非空字符串均可。会出现在 broker 日志与监控里,用于区分应用。\n */\n clientId: string;\n\n /**\n * 传给连接层的 TLS 配置。不设则沿用客户端默认。\n * 对象里的证书和私钥只接受 PEM 字符串、Buffer,或由它们组成的数组。\n */\n ssl?: Ssl;\n\n /**\n * SASL 认证。不设则不认证。\n * `aws` 当前客户端不支持,传入会在连接前抛错。\n * `oauthbearer` 只需返回 `value`。\n */\n sasl?: Sasl;\n\n /**\n * 连接超时。毫秒数或可读时长,如 `1_000`、`'1s'`。不设则沿用客户端默认。\n */\n connectionTimeout?: DurationInput;\n\n /**\n * 请求超时。毫秒数或可读时长,如 `30_000`、`'30s'`。不设则沿用客户端默认。\n */\n requestTimeout?: DurationInput;\n\n /** 是否允许 broker 自动建主题。默认 `false`。 */\n allowAutoTopicCreation?: boolean;\n\n /**\n * 幂等生产者。默认 `true`,此时 `acks` 必须为 `-1`。\n * 开启后在途请求为 5,重试次数为 `(2 ** 31) - 1`,队列为先进先出。\n */\n idempotent?: boolean;\n\n /**\n * 生产者确认级别。`-1` 全部副本,`1` 仅 leader,`0` 不等待。默认 `-1`。\n */\n acks?: -1 | 0 | 1;\n\n /**\n * 单条消息(值、分区键、header)的字节上限。默认 1 MiB。\n * 超过则拒绝发送,消费侧也拒绝解析。\n * 传给客户端的协议上限与此相同,并限制在 1000 到 1000000000。\n * 消费拉取上限只在这个值更大时上调。\n */\n maxMessageBytes?: number;\n\n /**\n * 消费组会话超时。毫秒数或可读时长,如 `30_000`、`'30s'`。默认 `'30s'`。\n */\n sessionTimeout?: DurationInput;\n\n /**\n * 处理消息期间自动心跳的间隔。毫秒数或可读时长,如 `3_000`、`'3s'`。\n * 未设置时取 `min(3s, sessionTimeout / 3)`。\n * 大于等于会话超时时拒绝创建。\n * 小于等于 `0` 时本库不再按间隔调用心跳回调。客户端自己的会话心跳仍会继续。\n */\n heartbeatInterval?: DurationInput;\n\n /** 把消息体编码成字节。默认 JSON。 */\n encode?: (value: unknown) => Buffer;\n\n /** 把消息字节解成消息体。默认 JSON。 */\n decode?: (buffer: Buffer) => unknown;\n }\n\n export interface SendOptions {\n /**\n * 分区键。相同值进入同一分区,从而保证同键消息有序。\n * 不传则由客户端分区器分配。\n */\n partitionKey?: string;\n /**\n * 消息头:跟消息体分开的元数据,消费端在 `ctx.meta.headers` 读取。\n * 典型用途:链路追踪(`traceId`)、报文版本、中间件按头过滤,而不必塞进业务 JSON。\n * 键值均为字符串,会计入 `maxMessageBytes`;同一键多个值时消费侧只保留最后一个。\n */\n headers?: Record<string, string>;\n /** 指定分区编号。与 `partitionKey` 同时传时,以本字段为准。 */\n partitionId?: number;\n }\n\n /** broker 对一条消息的回执。 */\n export interface Receipt {\n /** 写入的主题名。 */\n topic: string;\n /** 写入的分区编号。 */\n partitionId: number;\n /** 写入后的偏移量;`acks` 为 `0` 或 broker 未返回时为 `null`。 */\n offset: string | null;\n }\n\n /**\n * 消费到的消息位置与元数据,会出现在处理函数的 `ctx.meta` 上。\n */\n export interface Meta {\n /** 主题名,与 `defineKafkaTopic` 登记的名字一致。 */\n topic: string;\n /** 实际落入的分区编号。 */\n partitionId: number;\n /** 本分区内的消息偏移量(字符串,避免超过 JS 安全整数)。 */\n offset: string;\n /** broker 侧消息时间戳(毫秒字符串)。 */\n timestamp: string;\n /**\n * 生产时的分区键;未设置则为 `null`。\n * 同键消息进同一分区,从而有序;不是业务单号。\n */\n partitionKey: string | null;\n /**\n * 生产时附带的消息头;键值均为字符串。\n * 同一键有多个值时只保留最后一个;没有头时为空对象。\n */\n headers: Record<string, string>;\n }\n\n /**\n * 消费处理函数与 `middleware.kafka` 的上下文。\n * `value` 为消息体,`recordKey` 为本条记录稳定标识,`meta` 为 broker 位置与消息元数据,\n * `logger` 与 `createKafkaService` 传入的相同。`mount` 注入的属性也会出现在 `ctx` 上。\n */\n export type Context<T = unknown> = {\n /** 经主题规则校验后的消息体。 */\n value: T;\n /** 与 `createKafkaService` 传入的相同;中间件与处理函数共用。 */\n logger: Logger;\n /**\n * 本消费组视角下这条记录的稳定标识:`groupId:主题:分区:偏移量`,\n * 如 `billing:order.created:0:9`。用于日志关联或去重键,不是分区键,也不是业务单号。\n */\n recordKey: string;\n /** broker 侧位置与消息元数据(主题、分区、偏移量、头等)。 */\n meta: Meta;\n } & Props;\n\n export type Handler<T> = (ctx: Context<T>) => void | Promise<void>;\n}\n","import type { Validator, ValidatorToken } from '@aomex/common';\nimport { i18n } from '../i18n';\nimport type { IsKafkaValue } from './types';\n\n/** Kafka 主题名最大长度。 */\nconst TOPIC_NAME_MAX = 249;\n\n/** 字母、数字、`.`、`_`、`-`。 */\nconst TOPIC_NAME_RE = /^[a-zA-Z0-9._-]+$/;\n\n/**\n * 一份主题契约:名字和校验规则。生产和消费都引用它。\n * 请用 {@link defineKafkaTopic} 创建;构造函数为 `protected`,禁止业务侧直接 `new`。\n * 建议放在 `src/topics/`,文件名以 `.topic.ts` 结尾,变量名以 `Topic` 结尾,\n * 如 `order-created.topic.ts` 里的 `orderCreatedTopic`。\n */\nexport class KafkaTopic<T> {\n readonly name: string;\n readonly rule: ValidatorToken;\n /** 仅用于把消息体类型留在实例上。 */\n declare private readonly valueType: T;\n\n protected constructor(name: string, rule: ValidatorToken) {\n KafkaTopic.assertName(name);\n this.name = name;\n this.rule = rule;\n }\n\n /**\n * 供 {@link defineKafkaTopic} 调用;带「消息体须可 JSON 还原」的类型门禁。\n */\n protected static create<T extends ValidatorToken>(\n name: string,\n rule: IsKafkaValue<Validator.Infer<T>> extends true ? T : never,\n ): KafkaTopic<Validator.Infer<T>> {\n return new KafkaTopic(name, rule);\n }\n\n /**\n * 主题名须非空、不超过 249 字符,且只含字母、数字、`.`、`_`、`-`。\n * 不能是 `.` 或 `..`。\n */\n private static assertName(name: string): void {\n if (name.length === 0) {\n throw new Error(i18n.t('empty_topic'));\n }\n if (name.length > TOPIC_NAME_MAX) {\n throw new Error(\n i18n.t('topic_name_too_long', {\n length: String(name.length),\n max: String(TOPIC_NAME_MAX),\n }),\n );\n }\n if (name === '.' || name === '..' || !TOPIC_NAME_RE.test(name)) {\n throw new Error(i18n.t('invalid_topic_name', { topic: name }));\n }\n }\n}\n\n/**\n * 声明一个主题。建议每个主题一个文件,放在 `src/topics/`,文件名以 `.topic.ts` 结尾。\n *\n * ```ts\n * // src/topics/order-created.topic.ts\n * export const orderCreatedTopic = defineKafkaTopic('order.created', {\n * orderId: rule.string(),\n * amount: rule.number(),\n * });\n * ```\n */\nexport function defineKafkaTopic<T extends ValidatorToken>(\n name: string,\n rule: IsKafkaValue<Validator.Infer<T>> extends true ? T : never,\n): KafkaTopic<Validator.Infer<T>> {\n return KafkaTopic['create'](name, rule);\n}\n"],"mappings":";;;;AAEA,MAAa,KAAK,KAAK,OAAO;CAC5B,eAAe;CACf,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,iBAAiB;CACjB,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,QAAQ;CACR,mBAAmB;CACnB,cAAc;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,8BAA8B;CAC9B,kBAAkB;CAClB,iBAAiB;CACjB,2BAA2B;AAC7B,CAAC;;ACtBD,MAAa,KAAK,KAAK,UAAU,EAAE,CAAC,CAAC,OAAO;CAC1C,eAAe;CACf,cAAc;CACd,iBAAiB;CACjB,gBAAgB;CAChB,aAAa;CACb,oBAAoB;CACpB,qBAAqB;CACrB,iBAAiB;CACjB,gBAAgB;CAChB,iBAAiB;CACjB,mBAAmB;CACnB,QAAQ;CACR,mBAAmB;CACnB,cAAc;CACd,eAAe;CACf,eAAe;CACf,eAAe;CACf,gBAAgB;CAChB,8BAA8B;CAC9B,kBAAkB;CAClB,iBAAiB;CACjB,2BAA2B;AAC7B,CAAC;;ACtBD,MAAa,OAAO,WAAW;CAC7B;CACA;CACA,OAAO,SAAS,OAAO,IAAI,IAAI,aAAa,KAAK,MAAM,YAAY,GAAG,CAAC,CAAC;AAC1E,CAAC;;;;;ACoBD,IAAa,kBAAb,cAAoE,WAAkB;CAIpF,YACE,MACA;EACA,MAAM,EAAE,OACN,OAAO,SAAS,aACX,EAAE,IAAI,KAAK,IACZ;EACN,MAAM,EAAE;CACV;AACF;AAEA,WAAW,SAAS,SAAS,eAAe;;;;;;;ACsB5C,IAA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L,YAAY,cAAc,KAAK;GAC/B,eAAe;EACjB;CACF;AACF;;;ACtzBA,MAAM,iBAAiB;;AAGvB,MAAM,gBAAgB;;;;;;;AAQtB,IAAa,aAAb,MAAa,WAAc;CACzB;CACA;CAIA,YAAsB,MAAc,MAAsB;EACxD,WAAW,WAAW,IAAI;EAC1B,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;;;;CAKA,OAAiB,OACf,MACA,MACgC;EAChC,OAAO,IAAI,WAAW,MAAM,IAAI;CAClC;;;;;CAMA,OAAe,WAAW,MAAoB;EAC5C,IAAI,KAAK,WAAW,GAClB,MAAM,IAAI,MAAM,KAAK,EAAE,aAAa,CAAC;EAEvC,IAAI,KAAK,SAAS,gBAChB,MAAM,IAAI,MACR,KAAK,EAAE,uBAAuB;GAC5B,QAAQ,OAAO,KAAK,MAAM;GAC1B,KAAK,OAAO,cAAc;EAC5B,CAAC,CACH;EAEF,IAAI,SAAS,OAAO,SAAS,QAAQ,CAAC,cAAc,KAAK,IAAI,GAC3D,MAAM,IAAI,MAAM,KAAK,EAAE,sBAAsB,EAAE,OAAO,KAAK,CAAC,CAAC;CAEjE;AACF;;;;;;;;;;;;AAaA,SAAgB,iBACd,MACA,MACgC;CAChC,OAAO,WAAW,SAAS,CAAC,MAAM,IAAI;AACxC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aomex/kafka",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "4.7.1-alpha.2c491171.0",
|
|
4
|
+
"description": "类型安全的 Kafka 生产与消费",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git@github.com:aomex/aomex.git"
|
|
8
|
+
},
|
|
9
|
+
"homepage": "https://aomex.js.org",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"type": "module",
|
|
12
|
+
"sideEffects": [
|
|
13
|
+
"./dist/override/kafka-middleware.js"
|
|
14
|
+
],
|
|
15
|
+
"types": "dist/index.d.ts",
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"import": "./dist/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./package.json": "./package.json"
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist",
|
|
25
|
+
"package.json",
|
|
26
|
+
"README.md",
|
|
27
|
+
"CHANGELOG.md"
|
|
28
|
+
],
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@aomex/common": "^4.0.0",
|
|
34
|
+
"@aomex/logger": "^4.0.0"
|
|
35
|
+
},
|
|
36
|
+
"dependencies": {
|
|
37
|
+
"@aomex/internal-file-import": "4.7.1-alpha.2c491171.0",
|
|
38
|
+
"@aomex/internal-tools": "4.7.1-alpha.2c491171.0",
|
|
39
|
+
"@confluentinc/kafka-javascript": "^1.11.0"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"@aomex/common": "4.7.1-alpha.2c491171.0",
|
|
43
|
+
"@aomex/logger": "4.7.1-alpha.2c491171.0"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {}
|
|
6
46
|
}
|