@midwayjs/kafka 4.0.0-alpha.1 → 4.0.0-beta.2

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 CHANGED
@@ -12,4 +12,4 @@ Document: [https://midwayjs.org](https://midwayjs.org)
12
12
 
13
13
  ## License
14
14
 
15
- [MIT]((http://github.com/midwayjs/midway/blob/master/LICENSE))
15
+ [MIT]((https://github.com/midwayjs/midway/blob/master/LICENSE))
@@ -1,3 +1,5 @@
1
+ import { IMidwayContainer } from '@midwayjs/core';
1
2
  export declare class KafkaConfiguration {
3
+ onReady(container: IMidwayContainer): Promise<void>;
2
4
  }
3
5
  //# sourceMappingURL=configuration.d.ts.map
@@ -8,7 +8,11 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
9
  exports.KafkaConfiguration = void 0;
10
10
  const core_1 = require("@midwayjs/core");
11
+ const service_1 = require("./service");
11
12
  let KafkaConfiguration = class KafkaConfiguration {
13
+ async onReady(container) {
14
+ await container.getAsync(service_1.KafkaProducerFactory);
15
+ }
12
16
  };
13
17
  exports.KafkaConfiguration = KafkaConfiguration;
14
18
  exports.KafkaConfiguration = KafkaConfiguration = __decorate([
@@ -17,9 +21,7 @@ exports.KafkaConfiguration = KafkaConfiguration = __decorate([
17
21
  importConfigs: [
18
22
  {
19
23
  default: {
20
- kafka: {
21
- contextLoggerApplyLogger: 'kafkaLogger',
22
- },
24
+ kafka: {},
23
25
  midwayLogger: {
24
26
  clients: {
25
27
  kafkaLogger: {
@@ -1,14 +1,13 @@
1
- import { BaseFramework, ILogger, TypedResourceManager } from '@midwayjs/core';
1
+ import { BaseFramework, TypedResourceManager } from '@midwayjs/core';
2
2
  import { IKafkaConsumerInitOptions, IKafkaConsumer, IMidwayKafkaContext } from './interface';
3
3
  import { Kafka, Consumer } from 'kafkajs';
4
4
  export declare class MidwayKafkaFramework extends BaseFramework<any, IMidwayKafkaContext, any> {
5
5
  protected LogCreator: any;
6
6
  protected typedResourceManager: TypedResourceManager<Consumer, IKafkaConsumerInitOptions, IKafkaConsumer>;
7
+ protected frameworkLoggerName: string;
7
8
  configure(): any;
8
- kafKaLogger: ILogger;
9
9
  applicationInitialize(): Promise<void>;
10
10
  run(): Promise<void>;
11
- private loadLegacySubscriber;
12
11
  getConsumer(subscriberNameOrInstanceName: string): any;
13
12
  getKafka(instanceName: string): Kafka;
14
13
  getFrameworkName(): string;
package/dist/framework.js CHANGED
@@ -5,13 +5,9 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key,
5
5
  else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
6
  return c > 3 && r && Object.defineProperty(target, key, r), r;
7
7
  };
8
- var __metadata = (this && this.__metadata) || function (k, v) {
9
- if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
- };
11
8
  Object.defineProperty(exports, "__esModule", { value: true });
12
9
  exports.MidwayKafkaFramework = void 0;
13
10
  const core_1 = require("@midwayjs/core");
14
- const kafka_1 = require("./kafka");
15
11
  const decorator_1 = require("./decorator");
16
12
  const kafkajs_1 = require("kafkajs");
17
13
  const manager_1 = require("./manager");
@@ -30,197 +26,86 @@ const toMidwayLogLevel = level => {
30
26
  }
31
27
  };
32
28
  let MidwayKafkaFramework = class MidwayKafkaFramework extends core_1.BaseFramework {
29
+ constructor() {
30
+ super(...arguments);
31
+ this.frameworkLoggerName = 'kafkaLogger';
32
+ }
33
33
  configure() {
34
34
  return this.configService.getConfiguration('kafka');
35
35
  }
36
36
  async applicationInitialize() {
37
37
  this.LogCreator = logLevel => {
38
- const logger = this.kafKaLogger;
38
+ const logger = this.logger;
39
39
  return ({ level, log }) => {
40
40
  const lvl = toMidwayLogLevel(level);
41
41
  const { message, ...extra } = log;
42
42
  logger?.[lvl](message, extra);
43
43
  };
44
44
  };
45
- // Create a connection manager
46
- if (this.configurationOptions['kafkaConfig']) {
47
- this.app = new kafka_1.KafkaConsumerServer({
48
- logger: this.kafKaLogger,
49
- ...this.configurationOptions,
50
- });
51
- }
52
- else {
53
- this.app = {};
54
- }
45
+ this.app = {};
55
46
  }
56
47
  async run() {
57
- if (this.configurationOptions['kafkaConfig']) {
58
- try {
59
- await this.app.connect(this.configurationOptions.kafkaConfig, this.configurationOptions.consumerConfig);
60
- await this.loadLegacySubscriber();
61
- this.kafKaLogger.info('Kafka consumer server start success');
62
- }
63
- catch (error) {
64
- this.kafKaLogger.error('Kafka consumer connect fail', error);
65
- await this.app.closeConnection();
66
- }
48
+ const { consumer } = this.configurationOptions;
49
+ if (!consumer)
50
+ return;
51
+ const subscriberMap = {};
52
+ // find subscriber
53
+ const subscriberModules = core_1.DecoratorManager.listModule(decorator_1.KAFKA_DECORATOR_KEY);
54
+ for (const subscriberModule of subscriberModules) {
55
+ const subscriberName = core_1.MetadataManager.getOwnMetadata(decorator_1.KAFKA_DECORATOR_KEY, subscriberModule);
56
+ subscriberMap[subscriberName] = subscriberModule;
67
57
  }
68
- else {
69
- const { consumer } = this.configurationOptions;
70
- if (!consumer)
71
- return;
72
- const subscriberMap = {};
73
- // find subscriber
74
- const subscriberModules = core_1.DecoratorManager.listModule(decorator_1.KAFKA_DECORATOR_KEY);
75
- for (const subscriberModule of subscriberModules) {
76
- const subscriberName = core_1.MetadataManager.getOwnMetadata(decorator_1.KAFKA_DECORATOR_KEY, subscriberModule);
77
- subscriberMap[subscriberName] = subscriberModule;
78
- }
79
- this.typedResourceManager = new core_1.TypedResourceManager({
80
- initializeValue: consumer,
81
- initializeClzProvider: subscriberMap,
82
- resourceInitialize: async (resourceInitializeConfig, resourceName) => {
83
- let client;
84
- if (resourceInitializeConfig.kafkaInstanceRef) {
85
- client = manager_1.KafkaManager.getInstance().getKafkaInstance(resourceInitializeConfig.kafkaInstanceRef);
86
- if (!client) {
87
- throw new core_1.MidwayCommonError(`kafka instance ${resourceInitializeConfig.kafkaInstanceRef} not found`);
88
- }
58
+ this.typedResourceManager = new core_1.TypedResourceManager({
59
+ initializeValue: consumer,
60
+ initializeClzProvider: subscriberMap,
61
+ resourceInitialize: async (resourceInitializeConfig, resourceName) => {
62
+ let client;
63
+ if (resourceInitializeConfig.kafkaInstanceRef) {
64
+ client = manager_1.KafkaManager.getInstance().getKafkaInstance(resourceInitializeConfig.kafkaInstanceRef);
65
+ if (!client) {
66
+ throw new core_1.MidwayCommonError(`kafka instance ${resourceInitializeConfig.kafkaInstanceRef} not found`);
89
67
  }
90
- else {
91
- client = new kafkajs_1.Kafka({
92
- logCreator: this.LogCreator,
93
- ...resourceInitializeConfig.connectionOptions,
94
- });
95
- manager_1.KafkaManager.getInstance().addKafkaInstance(resourceName, client);
96
- }
97
- const consumer = client.consumer(resourceInitializeConfig.consumerOptions);
98
- await consumer.connect();
99
- await consumer.subscribe(resourceInitializeConfig.subscribeOptions);
100
- return consumer;
101
- },
102
- resourceBinding: async (ClzProvider, resourceInitializeConfig, consumer) => {
103
- const runMethod = ClzProvider.prototype['eachBatch']
104
- ? 'eachBatch'
105
- : 'eachMessage';
106
- const runConfig = {
107
- ...resourceInitializeConfig.consumerRunConfig,
108
- };
109
- runConfig[runMethod] = async (payload) => {
110
- const ctx = this.app.createAnonymousContext();
111
- const fn = await this.applyMiddleware(async (ctx) => {
112
- ctx.payload = payload;
113
- ctx.consumer = consumer;
114
- const instance = await ctx.requestContext.getAsync(ClzProvider);
115
- return await instance[runMethod].call(instance, payload, ctx);
116
- });
117
- return await fn(ctx);
118
- };
119
- return runConfig;
120
- },
121
- resourceStart: async (resource, resourceInitializeConfig, resourceBindingResult) => {
122
- await resource.run(resourceBindingResult);
123
- },
124
- resourceDestroy: async (resource) => {
125
- await resource.disconnect();
126
- },
127
- });
128
- await this.typedResourceManager.init();
129
- await this.typedResourceManager.start();
130
- }
131
- }
132
- async loadLegacySubscriber() {
133
- const subscriberModules = core_1.DecoratorManager.listModule(core_1.MS_CONSUMER_KEY, module => {
134
- const metadata = core_1.MetadataManager.getOwnMetadata(core_1.MS_CONSUMER_KEY, module);
135
- return metadata.type === core_1.MSListenerType.KAFKA;
136
- });
137
- for (const module of subscriberModules) {
138
- const data = (0, core_1.listPropertyDataFromClass)(core_1.MS_CONSUMER_KEY, module);
139
- const topicTitles = [...new Set(data.map(e => e[0].topic))];
140
- const midwayConsumerConfigs = topicTitles.map(e => {
141
- const midwayConsumerConfig = {
142
- topic: e,
143
- subscription: {},
144
- runConfig: {},
145
- };
146
- const consumerParams = data
147
- .map(value => {
148
- if (value[0].topic === midwayConsumerConfig.topic) {
149
- return Object.assign(midwayConsumerConfig, value[0]);
150
- }
151
- })
152
- .filter(e => e && true);
153
- if (consumerParams && Object.keys(consumerParams[0]).length > 0) {
154
- return consumerParams[0];
155
68
  }
156
- return midwayConsumerConfig;
157
- });
158
- midwayConsumerConfigs.forEach(async (e) => {
159
- await this.app.connection.subscribe(Object.assign({
160
- topics: topicTitles,
161
- }, e.subscription));
162
- await this.app.connection.run(Object.assign(e.runConfig, {
163
- eachMessage: async (payload) => {
164
- const { topic, partition, message } = payload;
165
- let propertyKey;
166
- for (const methodBindListeners of data) {
167
- for (const listenerOptions of methodBindListeners) {
168
- if (topic === listenerOptions.topic) {
169
- propertyKey = listenerOptions.propertyKey;
170
- const ctx = {
171
- topic: topic,
172
- partition: partition,
173
- message: message,
174
- commitOffsets: (offset) => {
175
- return this.app.connection.commitOffsets([
176
- {
177
- topic: topic,
178
- partition: partition,
179
- offset,
180
- },
181
- ]);
182
- },
183
- payload,
184
- consumer: this.app.connection,
185
- };
186
- this.app.createAnonymousContext(ctx);
187
- if (typeof propertyKey === 'string') {
188
- const isPassed = await this.app
189
- .getFramework()
190
- .runGuard(ctx, module, propertyKey);
191
- if (!isPassed) {
192
- throw new core_1.MidwayInvokeForbiddenError(propertyKey, module);
193
- }
194
- }
195
- const ins = await ctx.requestContext.getAsync(module);
196
- const fn = await this.applyMiddleware(async () => {
197
- return await ins[propertyKey].call(ins, message);
198
- });
199
- try {
200
- const result = await fn(ctx);
201
- // 返回为undefined,下面永远不会执行
202
- if (result) {
203
- const res = await this.app.connection.commitOffsets([
204
- {
205
- topic: topic,
206
- partition: partition,
207
- offset: message.offset,
208
- },
209
- ]);
210
- return res;
211
- }
212
- }
213
- catch (error) {
214
- // 记录偏移量提交的异常情况
215
- this.logger.error(error);
216
- }
217
- }
218
- }
219
- }
220
- },
221
- }));
222
- });
223
- }
69
+ else {
70
+ client = new kafkajs_1.Kafka({
71
+ logCreator: this.LogCreator,
72
+ ...resourceInitializeConfig.connectionOptions,
73
+ });
74
+ manager_1.KafkaManager.getInstance().addKafkaInstance(resourceName, client);
75
+ }
76
+ const consumer = client.consumer(resourceInitializeConfig.consumerOptions);
77
+ await consumer.connect();
78
+ await consumer.subscribe(resourceInitializeConfig.subscribeOptions);
79
+ return consumer;
80
+ },
81
+ resourceBinding: async (ClzProvider, resourceInitializeConfig, consumer) => {
82
+ const runMethod = ClzProvider.prototype['eachBatch']
83
+ ? 'eachBatch'
84
+ : 'eachMessage';
85
+ const runConfig = {
86
+ ...resourceInitializeConfig.consumerRunConfig,
87
+ };
88
+ runConfig[runMethod] = async (payload) => {
89
+ const ctx = this.app.createAnonymousContext();
90
+ const fn = await this.applyMiddleware(async (ctx) => {
91
+ ctx.payload = payload;
92
+ ctx.consumer = consumer;
93
+ const instance = await ctx.requestContext.getAsync(ClzProvider);
94
+ return await instance[runMethod].call(instance, payload, ctx);
95
+ });
96
+ return await fn(ctx);
97
+ };
98
+ return runConfig;
99
+ },
100
+ resourceStart: async (resource, resourceInitializeConfig, resourceBindingResult) => {
101
+ await resource.run(resourceBindingResult);
102
+ },
103
+ resourceDestroy: async (resource) => {
104
+ await resource.disconnect();
105
+ },
106
+ });
107
+ await this.typedResourceManager.init();
108
+ await this.typedResourceManager.start();
224
109
  }
225
110
  getConsumer(subscriberNameOrInstanceName) {
226
111
  if (this.typedResourceManager) {
@@ -240,10 +125,6 @@ let MidwayKafkaFramework = class MidwayKafkaFramework extends core_1.BaseFramewo
240
125
  }
241
126
  };
242
127
  exports.MidwayKafkaFramework = MidwayKafkaFramework;
243
- __decorate([
244
- (0, core_1.Logger)('kafkaLogger'),
245
- __metadata("design:type", Object)
246
- ], MidwayKafkaFramework.prototype, "kafKaLogger", void 0);
247
128
  exports.MidwayKafkaFramework = MidwayKafkaFramework = __decorate([
248
129
  (0, core_1.Framework)()
249
130
  ], MidwayKafkaFramework);
package/dist/service.js CHANGED
@@ -18,7 +18,9 @@ let KafkaProducerFactory = class KafkaProducerFactory extends core_1.ServiceFact
18
18
  return 'kafka:producer';
19
19
  }
20
20
  async init() {
21
- await this.initClients(this.pubConfig);
21
+ await this.initClients(this.pubConfig, {
22
+ concurrent: true,
23
+ });
22
24
  }
23
25
  async createClient(config, clientName) {
24
26
  const { connectionOptions, producerOptions, kafkaInstanceRef } = config;
@@ -77,7 +79,9 @@ let KafkaAdminFactory = class KafkaAdminFactory extends core_1.ServiceFactory {
77
79
  return 'kafka:admin';
78
80
  }
79
81
  async init() {
80
- await this.initClients(this.adminConfig);
82
+ await this.initClients(this.adminConfig, {
83
+ concurrent: true,
84
+ });
81
85
  }
82
86
  async createClient(config, clientName) {
83
87
  const { connectionOptions, adminOptions, kafkaInstanceRef } = config;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/kafka",
3
- "version": "4.0.0-alpha.1",
3
+ "version": "4.0.0-beta.2",
4
4
  "description": "Midway Framework for kafka",
5
5
  "main": "dist/index.js",
6
6
  "typings": "index.d.ts",
@@ -33,14 +33,14 @@
33
33
  },
34
34
  "homepage": "https://github.com/midwayjs/midway#readme",
35
35
  "devDependencies": {
36
- "@midwayjs/core": "^4.0.0-alpha.1",
37
- "@midwayjs/mock": "^4.0.0-alpha.1"
36
+ "@midwayjs/core": "^4.0.0-beta.2",
37
+ "@midwayjs/mock": "^4.0.0-beta.2"
38
38
  },
39
39
  "dependencies": {
40
40
  "kafkajs": "2.2.4"
41
41
  },
42
42
  "engines": {
43
- "node": ">=12"
43
+ "node": ">=20"
44
44
  },
45
- "gitHead": "14bb4da91805a1cf52f190c0d37a74b395dd6372"
45
+ "gitHead": "53bfef4c5279da5f09025e4610bdbf64f94f60bd"
46
46
  }
package/dist/kafka.d.ts DELETED
@@ -1,15 +0,0 @@
1
- /// <reference types="node" />
2
- /// <reference types="node" />
3
- import { Consumer, ConsumerConfig, KafkaConfig } from 'kafkajs';
4
- import { ILogger } from '@midwayjs/core';
5
- import { EventEmitter } from 'stream';
6
- export declare class KafkaConsumerServer extends EventEmitter {
7
- protected loggers: ILogger;
8
- connection: Consumer;
9
- constructor(options?: any);
10
- bindError(): void;
11
- connect(options: KafkaConfig, consumerOptions: ConsumerConfig): Promise<void>;
12
- protected closeConnection(): Promise<void>;
13
- close(): Promise<void>;
14
- }
15
- //# sourceMappingURL=kafka.d.ts.map
package/dist/kafka.js DELETED
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KafkaConsumerServer = void 0;
4
- const kafkajs_1 = require("kafkajs");
5
- const stream_1 = require("stream");
6
- class KafkaConsumerServer extends stream_1.EventEmitter {
7
- constructor(options = {}) {
8
- super();
9
- this.connection = null;
10
- this.loggers = options.logger;
11
- this.bindError();
12
- }
13
- bindError() {
14
- this.on('error', err => {
15
- this.loggers.error(err);
16
- });
17
- }
18
- async connect(options, consumerOptions) {
19
- this.connection = new kafkajs_1.Kafka(options).consumer(consumerOptions);
20
- this.connection.on('consumer.connect', () => {
21
- this.loggers.info('Kafka consumer connected!');
22
- });
23
- this.connection.on('consumer.disconnect', err => {
24
- if (err) {
25
- this.loggers.error('Kafka consumer disconnected', err);
26
- }
27
- else {
28
- this.loggers.info('Kafka consumer disconnected!');
29
- }
30
- });
31
- }
32
- async closeConnection() {
33
- try {
34
- if (this.connection) {
35
- await this.connection.disconnect();
36
- }
37
- this.loggers.debug('Kafka consumer connection close success');
38
- }
39
- catch (err) {
40
- this.loggers.error('Kafka consumer connection close error', err);
41
- }
42
- finally {
43
- this.connection = null;
44
- }
45
- }
46
- async close() {
47
- this.loggers.debug('Kafka consumer will be close');
48
- await this.closeConnection();
49
- }
50
- }
51
- exports.KafkaConsumerServer = KafkaConsumerServer;
52
- //# sourceMappingURL=kafka.js.map