-
Notifications
You must be signed in to change notification settings - Fork 0
/
producer.ts
164 lines (164 loc) · 4.8 KB
/
producer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import { injectable } from '@biorate/inversion';
import { Connector } from '@biorate/connector';
import { Kafka, Partitioners, ProducerRecord } from 'kafkajs';
import { counter, Counter, histogram, Histogram } from '@biorate/prometheus';
import { KafkaJSProducerCantConnectError } from '../errors';
import { IKafkaJSProducerConfig, IKafkaJSProducerConnection } from '../interfaces';
import { LogCreator } from '../logger';
/**
* @description KafkaJS producer connector
*
* ### Features:
* - producer connector manager for KafkaJS
*
* @example
* ```
* import { inject, container, Types, Core } from '@biorate/inversion';
* import { IConfig, Config } from '@biorate/config';
* import { KafkaJSProducerConnector } from '@biorate/kafkajs';
*
* class Root extends Core() {
* @inject(KafkaJSProducerConnector) public producer: KafkaJSProducerConnector;
* }
*
* container.bind<IConfig>(Types.Config).to(Config).inSingletonScope();
* container.bind<KafkaJSProducerConnector>(KafkaJSProducerConnector).toSelf().inSingletonScope();
* container.bind<Root>(Root).toSelf().inSingletonScope();
*
* container.get<IConfig>(Types.Config).merge({
* KafkaJSGlobal: {
* brokers: ['localhost:9092'],
* clientId: 'test-app',
* logLevel: 1,
* },
* KafkaJSProducer: [
* {
* name: 'producer',
* global: '#{KafkaJSGlobal}',
* },
* ],
* });
*
* (async () => {
* const topic = 'test-kafkajs';
* const root = container.get<Root>(Root);
* await root.$run();
* await root.producer!.current!.send({
* topic,
* messages: [
* { key: 'key 1', value: 'hello world 1' },
* { key: 'key 2', value: 'hello world 2' },
* { key: 'key 3', value: 'hello world 3' },
* ],
* });
* })();
* ```
*/
@injectable()
export class KafkaJSProducerConnector extends Connector<
IKafkaJSProducerConfig,
IKafkaJSProducerConnection
> {
/**
* @description Private connections storage
*/
private '#connections': Map<string, IKafkaJSProducerConnection>;
/**
* @description Private link to selected (used) connection
*/
private '#current': IKafkaJSProducerConnection | undefined;
/**
* @description Counter
*/
@counter({
name: 'kafka_producer_seconds_count',
help: 'Kafka producer seconds count',
labelNames: ['topic', 'status'],
})
protected counter: Counter;
/**
* @description Histogram
*/
@histogram({
name: 'kafka_producer_seconds',
help: 'Kafka producer seconds bucket',
labelNames: ['topic', 'status'],
buckets: [5, 10, 20, 50, 100, 300, 500, 1000, 2000, 3000, 5000, 10000],
})
protected histogram: Histogram;
/**
* @description Namespace path for fetching configuration
*/
protected readonly namespace = 'KafkaJSProducer';
/**
* @description Create connection
*/
protected async connect(config: IKafkaJSProducerConfig) {
let connection: IKafkaJSProducerConnection;
try {
connection = new Kafka({
logCreator: LogCreator,
...config.global,
}).producer({
createPartitioner: Partitioners[config.partitioner ?? 'DefaultPartitioner'],
...config.options,
});
await connection.connect();
} catch (e: unknown) {
throw new KafkaJSProducerCantConnectError(<Error>e);
}
return connection;
}
/**
* @description Send
*/
public async send(name: string, record: ProducerRecord) {
const connection = this.get(name);
const start = Date.now();
try {
const result = await connection.send(record);
this.histogram
.labels({ topic: record.topic, status: 200 })
.observe(Date.now() - start);
this.counter
.labels({ topic: record.topic, status: 200 })
.inc(record.messages.length);
return result;
} catch (e) {
this.histogram
.labels({ topic: record.topic, status: 400 })
.observe(Date.now() - start);
this.counter
.labels({ topic: record.topic, status: 400 })
.inc(record.messages.length);
throw e;
}
}
/**
* @description Transaction
*/
public async transaction(name: string, record: ProducerRecord) {
const connection = this.get(name);
const start = Date.now();
const transaction = await connection.transaction();
try {
await transaction.send(record);
await transaction.commit();
this.histogram
.labels({ topic: record.topic, status: 200 })
.observe(Date.now() - start);
this.counter
.labels({ topic: record.topic, status: 200 })
.inc(record.messages.length);
} catch (e) {
await transaction.abort();
this.histogram
.labels({ topic: record.topic, status: 400 })
.observe(Date.now() - start);
this.counter
.labels({ topic: record.topic, status: 400 })
.inc(record.messages.length);
throw e;
}
}
}