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

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: {
package/dist/decorator.js CHANGED
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.KafkaConsumer = exports.KAFKA_DECORATOR_KEY = void 0;
3
+ exports.KAFKA_DECORATOR_KEY = void 0;
4
+ exports.KafkaConsumer = KafkaConsumer;
4
5
  const core_1 = require("@midwayjs/core");
5
6
  exports.KAFKA_DECORATOR_KEY = 'rpc:kafka';
6
7
  function KafkaConsumer(consumerName) {
@@ -11,5 +12,4 @@ function KafkaConsumer(consumerName) {
11
12
  (0, core_1.Provide)()(target);
12
13
  };
13
14
  }
14
- exports.KafkaConsumer = KafkaConsumer;
15
15
  //# sourceMappingURL=decorator.js.map
@@ -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,85 @@ const toMidwayLogLevel = level => {
30
26
  }
31
27
  };
32
28
  let MidwayKafkaFramework = class MidwayKafkaFramework extends core_1.BaseFramework {
29
+ LogCreator;
30
+ typedResourceManager;
31
+ frameworkLoggerName = 'kafkaLogger';
33
32
  configure() {
34
33
  return this.configService.getConfiguration('kafka');
35
34
  }
36
35
  async applicationInitialize() {
37
36
  this.LogCreator = logLevel => {
38
- const logger = this.kafKaLogger;
37
+ const logger = this.logger;
39
38
  return ({ level, log }) => {
40
39
  const lvl = toMidwayLogLevel(level);
41
40
  const { message, ...extra } = log;
42
41
  logger?.[lvl](message, extra);
43
42
  };
44
43
  };
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
- }
44
+ this.app = {};
55
45
  }
56
46
  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
- }
47
+ const { consumer } = this.configurationOptions;
48
+ if (!consumer)
49
+ return;
50
+ const subscriberMap = {};
51
+ // find subscriber
52
+ const subscriberModules = core_1.DecoratorManager.listModule(decorator_1.KAFKA_DECORATOR_KEY);
53
+ for (const subscriberModule of subscriberModules) {
54
+ const subscriberName = core_1.MetadataManager.getOwnMetadata(decorator_1.KAFKA_DECORATOR_KEY, subscriberModule);
55
+ subscriberMap[subscriberName] = subscriberModule;
67
56
  }
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
- }
89
- }
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]);
57
+ this.typedResourceManager = new core_1.TypedResourceManager({
58
+ initializeValue: consumer,
59
+ initializeClzProvider: subscriberMap,
60
+ resourceInitialize: async (resourceInitializeConfig, resourceName) => {
61
+ let client;
62
+ if (resourceInitializeConfig.kafkaInstanceRef) {
63
+ client = manager_1.KafkaManager.getInstance().getKafkaInstance(resourceInitializeConfig.kafkaInstanceRef);
64
+ if (!client) {
65
+ throw new core_1.MidwayCommonError(`kafka instance ${resourceInitializeConfig.kafkaInstanceRef} not found`);
150
66
  }
151
- })
152
- .filter(e => e && true);
153
- if (consumerParams && Object.keys(consumerParams[0]).length > 0) {
154
- return consumerParams[0];
155
67
  }
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
- }
68
+ else {
69
+ client = new kafkajs_1.Kafka({
70
+ logCreator: this.LogCreator,
71
+ ...resourceInitializeConfig.connectionOptions,
72
+ });
73
+ manager_1.KafkaManager.getInstance().addKafkaInstance(resourceName, client);
74
+ }
75
+ const consumer = client.consumer(resourceInitializeConfig.consumerOptions);
76
+ await consumer.connect();
77
+ await consumer.subscribe(resourceInitializeConfig.subscribeOptions);
78
+ return consumer;
79
+ },
80
+ resourceBinding: async (ClzProvider, resourceInitializeConfig, consumer) => {
81
+ const runMethod = ClzProvider.prototype['eachBatch']
82
+ ? 'eachBatch'
83
+ : 'eachMessage';
84
+ const runConfig = {
85
+ ...resourceInitializeConfig.consumerRunConfig,
86
+ };
87
+ runConfig[runMethod] = async (payload) => {
88
+ const ctx = this.app.createAnonymousContext();
89
+ const fn = await this.applyMiddleware(async (ctx) => {
90
+ ctx.payload = payload;
91
+ ctx.consumer = consumer;
92
+ const instance = await ctx.requestContext.getAsync(ClzProvider);
93
+ return await instance[runMethod].call(instance, payload, ctx);
94
+ });
95
+ return await fn(ctx);
96
+ };
97
+ return runConfig;
98
+ },
99
+ resourceStart: async (resource, resourceInitializeConfig, resourceBindingResult) => {
100
+ await resource.run(resourceBindingResult);
101
+ },
102
+ resourceDestroy: async (resource) => {
103
+ await resource.disconnect();
104
+ },
105
+ });
106
+ await this.typedResourceManager.init();
107
+ await this.typedResourceManager.start();
224
108
  }
225
109
  getConsumer(subscriberNameOrInstanceName) {
226
110
  if (this.typedResourceManager) {
@@ -240,10 +124,6 @@ let MidwayKafkaFramework = class MidwayKafkaFramework extends core_1.BaseFramewo
240
124
  }
241
125
  };
242
126
  exports.MidwayKafkaFramework = MidwayKafkaFramework;
243
- __decorate([
244
- (0, core_1.Logger)('kafkaLogger'),
245
- __metadata("design:type", Object)
246
- ], MidwayKafkaFramework.prototype, "kafKaLogger", void 0);
247
127
  exports.MidwayKafkaFramework = MidwayKafkaFramework = __decorate([
248
128
  (0, core_1.Framework)()
249
129
  ], MidwayKafkaFramework);
package/dist/manager.js CHANGED
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.KafkaManager = void 0;
4
4
  class KafkaManager {
5
- constructor() {
6
- this.kafkaInstanceMap = new Map();
7
- }
5
+ kafkaInstanceMap = new Map();
6
+ static instance;
7
+ constructor() { }
8
8
  getKafkaInstance(name) {
9
9
  return this.kafkaInstanceMap.get(name);
10
10
  }
package/dist/service.js CHANGED
@@ -14,11 +14,15 @@ const core_1 = require("@midwayjs/core");
14
14
  const kafkajs_1 = require("kafkajs");
15
15
  const manager_1 = require("./manager");
16
16
  let KafkaProducerFactory = class KafkaProducerFactory extends core_1.ServiceFactory {
17
+ logger;
18
+ pubConfig;
17
19
  getName() {
18
20
  return 'kafka:producer';
19
21
  }
20
22
  async init() {
21
- await this.initClients(this.pubConfig);
23
+ await this.initClients(this.pubConfig, {
24
+ concurrent: true,
25
+ });
22
26
  }
23
27
  async createClient(config, clientName) {
24
28
  const { connectionOptions, producerOptions, kafkaInstanceRef } = config;
@@ -73,11 +77,15 @@ exports.KafkaProducerFactory = KafkaProducerFactory = __decorate([
73
77
  (0, core_1.Singleton)()
74
78
  ], KafkaProducerFactory);
75
79
  let KafkaAdminFactory = class KafkaAdminFactory extends core_1.ServiceFactory {
80
+ logger;
81
+ adminConfig;
76
82
  getName() {
77
83
  return 'kafka:admin';
78
84
  }
79
85
  async init() {
80
- await this.initClients(this.adminConfig);
86
+ await this.initClients(this.adminConfig, {
87
+ concurrent: true,
88
+ });
81
89
  }
82
90
  async createClient(config, clientName) {
83
91
  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.10",
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.10",
37
+ "@midwayjs/mock": "^4.0.0-beta.10"
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": "1b1856629913703f67304155aaf611ec936a81ac"
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