rocketmq-client-nodejs 1.0.8 → 1.1.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.
Files changed (159) hide show
  1. package/README.md +61 -0
  2. package/dist/client/BaseClient.d.ts +36 -1
  3. package/dist/client/BaseClient.js +176 -12
  4. package/dist/client/RpcClient.js +14 -2
  5. package/dist/client/RpcClientManager.d.ts +5 -0
  6. package/dist/client/RpcClientManager.js +25 -8
  7. package/dist/client/TelemetrySession.js +45 -10
  8. package/dist/consumer/ConsumeService.d.ts +2 -1
  9. package/dist/consumer/ConsumeService.js +7 -3
  10. package/dist/consumer/ConsumeTask.d.ts +6 -1
  11. package/dist/consumer/ConsumeTask.js +36 -5
  12. package/dist/consumer/Consumer.d.ts +13 -5
  13. package/dist/consumer/Consumer.js +85 -24
  14. package/dist/consumer/FifoConsumeService.d.ts +2 -1
  15. package/dist/consumer/FifoConsumeService.js +3 -3
  16. package/dist/consumer/LiteFifoConsumeService.d.ts +2 -1
  17. package/dist/consumer/LiteFifoConsumeService.js +3 -3
  18. package/dist/consumer/LitePushConsumerImpl.d.ts +12 -1
  19. package/dist/consumer/LitePushConsumerImpl.js +19 -4
  20. package/dist/consumer/LiteSimpleConsumer.d.ts +177 -0
  21. package/dist/consumer/LiteSimpleConsumer.js +126 -0
  22. package/dist/consumer/LiteSimpleConsumerImpl.d.ts +133 -0
  23. package/dist/consumer/LiteSimpleConsumerImpl.js +187 -0
  24. package/dist/consumer/LiteStandardConsumeService.d.ts +2 -1
  25. package/dist/consumer/LiteStandardConsumeService.js +3 -3
  26. package/dist/consumer/LiteSubscriptionManager.d.ts +27 -6
  27. package/dist/consumer/LiteSubscriptionManager.js +32 -24
  28. package/dist/consumer/ProcessQueue.d.ts +10 -0
  29. package/dist/consumer/ProcessQueue.js +43 -5
  30. package/dist/consumer/PushConsumer.d.ts +17 -0
  31. package/dist/consumer/PushConsumer.js +43 -4
  32. package/dist/consumer/PushConsumerGaugeObserver.d.ts +33 -0
  33. package/dist/consumer/PushConsumerGaugeObserver.js +60 -0
  34. package/dist/consumer/PushSubscriptionSettings.d.ts +8 -1
  35. package/dist/consumer/PushSubscriptionSettings.js +33 -6
  36. package/dist/consumer/SimpleConsumer.js +10 -1
  37. package/dist/consumer/StandardConsumeService.d.ts +2 -1
  38. package/dist/consumer/StandardConsumeService.js +3 -3
  39. package/dist/consumer/index.d.ts +1 -0
  40. package/dist/consumer/index.js +2 -1
  41. package/dist/exception/PayloadEmptyException.d.ts +20 -0
  42. package/dist/exception/PayloadEmptyException.js +28 -0
  43. package/dist/exception/StatusChecker.js +8 -1
  44. package/dist/exception/index.d.ts +1 -0
  45. package/dist/exception/index.js +2 -1
  46. package/dist/hook/Attribute.d.ts +26 -0
  47. package/dist/hook/Attribute.js +37 -0
  48. package/dist/hook/AttributeKey.d.ts +32 -0
  49. package/dist/hook/AttributeKey.js +43 -0
  50. package/dist/hook/CompositedMessageInterceptor.d.ts +31 -0
  51. package/dist/hook/CompositedMessageInterceptor.js +84 -0
  52. package/dist/hook/InflightRequestCountInterceptor.d.ts +28 -0
  53. package/dist/hook/InflightRequestCountInterceptor.js +44 -0
  54. package/dist/hook/MessageHookPoints.d.ts +54 -0
  55. package/dist/hook/MessageHookPoints.js +59 -0
  56. package/dist/hook/MessageHookPointsStatus.d.ts +24 -0
  57. package/dist/hook/MessageHookPointsStatus.js +29 -0
  58. package/dist/hook/MessageInterceptor.d.ts +34 -0
  59. package/dist/hook/MessageInterceptor.js +19 -0
  60. package/dist/hook/MessageInterceptorContext.d.ts +31 -0
  61. package/dist/hook/MessageInterceptorContext.js +19 -0
  62. package/dist/hook/MessageInterceptorContextImpl.d.ts +39 -0
  63. package/dist/hook/MessageInterceptorContextImpl.js +57 -0
  64. package/dist/hook/MessageMeterInterceptor.d.ts +39 -0
  65. package/dist/hook/MessageMeterInterceptor.js +149 -0
  66. package/dist/hook/index.d.ts +26 -0
  67. package/dist/hook/index.js +43 -0
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.js +2 -1
  70. package/dist/metrics/ClientMeter.d.ts +42 -0
  71. package/dist/metrics/ClientMeter.js +75 -0
  72. package/dist/metrics/ClientMeterManager.d.ts +42 -0
  73. package/dist/metrics/ClientMeterManager.js +127 -0
  74. package/dist/metrics/EmptyGaugeObserver.d.ts +28 -0
  75. package/dist/metrics/EmptyGaugeObserver.js +34 -0
  76. package/dist/metrics/GaugeEnum.d.ts +32 -0
  77. package/dist/metrics/GaugeEnum.js +37 -0
  78. package/dist/metrics/GaugeObserver.d.ts +29 -0
  79. package/dist/metrics/GaugeObserver.js +19 -0
  80. package/dist/metrics/HistogramEnum.d.ts +54 -0
  81. package/dist/metrics/HistogramEnum.js +71 -0
  82. package/dist/metrics/InvocationStatus.d.ts +26 -0
  83. package/dist/metrics/InvocationStatus.js +33 -0
  84. package/dist/metrics/Metric.d.ts +30 -0
  85. package/dist/metrics/Metric.js +44 -0
  86. package/dist/metrics/MetricLabels.d.ts +27 -0
  87. package/dist/metrics/MetricLabels.js +34 -0
  88. package/dist/metrics/index.d.ts +25 -0
  89. package/dist/metrics/index.js +42 -0
  90. package/dist/producer/Producer.js +33 -5
  91. package/dist/producer/PublishingLoadBalancer.js +9 -3
  92. package/dist/retry/CustomizedBackoffRetryPolicy.d.ts +37 -0
  93. package/dist/retry/CustomizedBackoffRetryPolicy.js +72 -0
  94. package/dist/retry/ExponentialBackoffRetryPolicy.js +10 -6
  95. package/dist/retry/RetryPolicy.d.ts +1 -1
  96. package/dist/retry/index.d.ts +1 -0
  97. package/dist/retry/index.js +2 -1
  98. package/dist/route/Endpoints.d.ts +6 -0
  99. package/dist/route/Endpoints.js +56 -4
  100. package/dist/route/IpNameResolver.d.ts +28 -0
  101. package/dist/route/IpNameResolver.js +104 -0
  102. package/dist/util/Semaphore.d.ts +47 -0
  103. package/dist/util/Semaphore.js +82 -0
  104. package/package.json +6 -2
  105. package/src/client/BaseClient.ts +202 -12
  106. package/src/client/RpcClient.ts +14 -1
  107. package/src/client/RpcClientManager.ts +27 -8
  108. package/src/client/TelemetrySession.ts +47 -9
  109. package/src/consumer/ConsumeService.ts +9 -2
  110. package/src/consumer/ConsumeTask.ts +43 -3
  111. package/src/consumer/Consumer.ts +103 -23
  112. package/src/consumer/FifoConsumeService.ts +4 -2
  113. package/src/consumer/LiteFifoConsumeService.ts +4 -2
  114. package/src/consumer/LitePushConsumerImpl.ts +21 -3
  115. package/src/consumer/LiteSimpleConsumer.ts +251 -0
  116. package/src/consumer/LiteSimpleConsumerImpl.ts +221 -0
  117. package/src/consumer/LiteStandardConsumeService.ts +4 -2
  118. package/src/consumer/LiteSubscriptionManager.ts +63 -36
  119. package/src/consumer/ProcessQueue.ts +44 -1
  120. package/src/consumer/PushConsumer.ts +54 -2
  121. package/src/consumer/PushConsumerGaugeObserver.ts +60 -0
  122. package/src/consumer/PushSubscriptionSettings.ts +38 -7
  123. package/src/consumer/SimpleConsumer.ts +9 -0
  124. package/src/consumer/StandardConsumeService.ts +4 -2
  125. package/src/consumer/index.ts +1 -0
  126. package/src/exception/PayloadEmptyException.ts +25 -0
  127. package/src/exception/StatusChecker.ts +7 -0
  128. package/src/exception/index.ts +1 -0
  129. package/src/hook/Attribute.ts +36 -0
  130. package/src/hook/AttributeKey.ts +42 -0
  131. package/src/hook/CompositedMessageInterceptor.ts +92 -0
  132. package/src/hook/InflightRequestCountInterceptor.ts +46 -0
  133. package/src/hook/MessageHookPoints.ts +55 -0
  134. package/src/hook/MessageHookPointsStatus.ts +25 -0
  135. package/src/hook/MessageInterceptor.ts +35 -0
  136. package/src/hook/MessageInterceptorContext.ts +33 -0
  137. package/src/hook/MessageInterceptorContextImpl.ts +68 -0
  138. package/src/hook/MessageMeterInterceptor.ts +162 -0
  139. package/src/hook/index.ts +27 -0
  140. package/src/index.ts +1 -0
  141. package/src/metrics/ClientMeter.ts +81 -0
  142. package/src/metrics/ClientMeterManager.ts +145 -0
  143. package/src/metrics/EmptyGaugeObserver.ts +36 -0
  144. package/src/metrics/GaugeEnum.ts +33 -0
  145. package/src/metrics/GaugeObserver.ts +32 -0
  146. package/src/metrics/HistogramEnum.ts +69 -0
  147. package/src/metrics/InvocationStatus.ts +28 -0
  148. package/src/metrics/Metric.ts +42 -0
  149. package/src/metrics/MetricLabels.ts +31 -0
  150. package/src/metrics/index.ts +26 -0
  151. package/src/producer/Producer.ts +37 -6
  152. package/src/producer/PublishingLoadBalancer.ts +8 -2
  153. package/src/retry/CustomizedBackoffRetryPolicy.ts +81 -0
  154. package/src/retry/ExponentialBackoffRetryPolicy.ts +11 -6
  155. package/src/retry/RetryPolicy.ts +1 -1
  156. package/src/retry/index.ts +1 -0
  157. package/src/route/Endpoints.ts +52 -3
  158. package/src/route/IpNameResolver.ts +119 -0
  159. package/src/util/Semaphore.ts +82 -0
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Hook points at which {@link MessageInterceptor}s are invoked, mirroring
20
+ * org.apache.rocketmq.client.java.hook.MessageHookPoints.
21
+ */
22
+ export enum MessageHookPoints {
23
+ /**
24
+ * The hook point of message publishing.
25
+ */
26
+ SEND = 'SEND',
27
+ /**
28
+ * The hook point of message reception.
29
+ */
30
+ RECEIVE = 'RECEIVE',
31
+ /**
32
+ * The hook point of message consumption.
33
+ */
34
+ CONSUME = 'CONSUME',
35
+ /**
36
+ * The hook point of message ack acknowledgement.
37
+ */
38
+ ACK = 'ACK',
39
+ /**
40
+ * The hook point of message changing invisible duration.
41
+ */
42
+ CHANGE_INVISIBLE_DURATION = 'CHANGE_INVISIBLE_DURATION',
43
+ /**
44
+ * The hook point of message transaction commit.
45
+ */
46
+ COMMIT_TRANSACTION = 'COMMIT_TRANSACTION',
47
+ /**
48
+ * The hook point of message transaction rollback.
49
+ */
50
+ ROLLBACK_TRANSACTION = 'ROLLBACK_TRANSACTION',
51
+ /**
52
+ * The hook point of forwarding message to DLQ.
53
+ */
54
+ FORWARD_TO_DLQ = 'FORWARD_TO_DLQ',
55
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ /**
19
+ * Status of a hook point invocation, mirroring
20
+ * org.apache.rocketmq.client.java.hook.MessageHookPointsStatus.
21
+ */
22
+ export enum MessageHookPointsStatus {
23
+ OK = 'OK',
24
+ ERROR = 'ERROR',
25
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { MessageView } from '../message/MessageView';
19
+ import { MessageInterceptorContext } from './MessageInterceptorContext';
20
+
21
+ /**
22
+ * Message passed to interceptors: either an outgoing message or a received one,
23
+ * mirroring org.apache.rocketmq.client.java.message.GeneralMessage.
24
+ */
25
+ export type GeneralMessage = MessageView | { topic: string };
26
+
27
+ /**
28
+ * Interface for intercepting ingoing/outgoing message before/after they are
29
+ * dispatched by client, mirroring
30
+ * org.apache.rocketmq.client.java.hook.MessageInterceptor.
31
+ */
32
+ export interface MessageInterceptor {
33
+ doBefore(context: MessageInterceptorContext, messages: GeneralMessage[]): void;
34
+ doAfter(context: MessageInterceptorContext, messages: GeneralMessage[]): void;
35
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Attribute } from './Attribute';
19
+ import { AttributeKey } from './AttributeKey';
20
+ import { MessageHookPoints } from './MessageHookPoints';
21
+ import { MessageHookPointsStatus } from './MessageHookPointsStatus';
22
+
23
+ /**
24
+ * Context carried through the message interceptor chain, mirroring
25
+ * org.apache.rocketmq.client.java.hook.MessageInterceptorContext.
26
+ */
27
+ export interface MessageInterceptorContext {
28
+ getMessageHookPoints(): MessageHookPoints;
29
+ getStatus(): MessageHookPointsStatus | undefined;
30
+ putAttribute<T>(key: AttributeKey<T>, value: Attribute<T>): void;
31
+ getAttribute<T>(key: AttributeKey<T>): Attribute<T> | undefined;
32
+ getAttributes(): Map<AttributeKey<any>, Attribute<any>>;
33
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Attribute } from './Attribute';
19
+ import { AttributeKey } from './AttributeKey';
20
+ import { MessageHookPoints } from './MessageHookPoints';
21
+ import { MessageHookPointsStatus } from './MessageHookPointsStatus';
22
+ import { MessageInterceptorContext } from './MessageInterceptorContext';
23
+
24
+ /**
25
+ * Default {@link MessageInterceptorContext} implementation, mirroring
26
+ * org.apache.rocketmq.client.java.hook.MessageInterceptorContextImpl.
27
+ */
28
+ export class MessageInterceptorContextImpl implements MessageInterceptorContext {
29
+ readonly #messageHookPoints: MessageHookPoints;
30
+ readonly #status: MessageHookPointsStatus | undefined;
31
+ readonly #attributes: Map<AttributeKey<any>, Attribute<any>>;
32
+
33
+ constructor(messageHookPoints: MessageHookPoints,
34
+ status?: MessageHookPointsStatus,
35
+ attributes?: Map<AttributeKey<any>, Attribute<any>>) {
36
+ this.#messageHookPoints = messageHookPoints;
37
+ this.#status = status;
38
+ this.#attributes = new Map(attributes ?? []);
39
+ }
40
+
41
+ /**
42
+ * Derive a new context from an existing one with the given status, e.g. once the
43
+ * outcome of the intercepted operation is known.
44
+ */
45
+ static withStatus(context: MessageInterceptorContext, status: MessageHookPointsStatus) {
46
+ return new MessageInterceptorContextImpl(context.getMessageHookPoints(), status, context.getAttributes());
47
+ }
48
+
49
+ getMessageHookPoints(): MessageHookPoints {
50
+ return this.#messageHookPoints;
51
+ }
52
+
53
+ getStatus(): MessageHookPointsStatus | undefined {
54
+ return this.#status;
55
+ }
56
+
57
+ putAttribute<T>(key: AttributeKey<T>, value: Attribute<T>) {
58
+ this.#attributes.set(key, value);
59
+ }
60
+
61
+ getAttribute<T>(key: AttributeKey<T>): Attribute<T> | undefined {
62
+ return this.#attributes.get(key) as Attribute<T> | undefined;
63
+ }
64
+
65
+ getAttributes(): Map<AttributeKey<any>, Attribute<any>> {
66
+ return this.#attributes;
67
+ }
68
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Attributes } from '@opentelemetry/api';
19
+ import { Attribute, AttributeKey, MessageHookPoints, MessageHookPointsStatus, MessageInterceptor, MessageInterceptorContext } from './';
20
+ import { GeneralMessage } from './MessageInterceptor';
21
+ import { MetricLabels } from '../metrics/MetricLabels';
22
+ import { InvocationStatus } from '../metrics/InvocationStatus';
23
+ import { HistogramEnum } from '../metrics/HistogramEnum';
24
+ import { ClientMeterManager } from '../metrics/ClientMeterManager';
25
+
26
+ /**
27
+ * Minimal message shape required to compute metric attributes / latencies.
28
+ * Covers both the producer's PublishingMessage (cast to GeneralMessage) and the
29
+ * consumer's MessageView (which implements GeneralMessage).
30
+ */
31
+ type MetricMessage = {
32
+ topic: string;
33
+ transportDeliveryTimestamp?: Date;
34
+ decodeTimestamp?: Date;
35
+ };
36
+
37
+ /**
38
+ * Records the four RocketMQ histograms around the SEND / RECEIVE / CONSUME hook
39
+ * points, mirroring org.apache.rocketmq.client.java.metrics.MessageMeterInterceptor.
40
+ *
41
+ * Unlike Java (which wires an AuthInterceptor + IpNameResolverFactory onto the
42
+ * export channel), the Node client signs each export request via a per-call
43
+ * metadata provider (see {@link ClientMeterManager}), so no auth plumbing is
44
+ * needed here.
45
+ */
46
+ export class MessageMeterInterceptor implements MessageInterceptor {
47
+ static readonly SEND_STOPWATCH_KEY = AttributeKey.create<number>('send_stopwatch');
48
+ static readonly CONSUME_STOPWATCH_KEY = AttributeKey.create<number>('consume_stopwatch');
49
+
50
+ constructor(
51
+ private readonly meterManager: ClientMeterManager,
52
+ private readonly clientId: string,
53
+ private readonly getConsumerGroup: () => string | undefined,
54
+ ) {
55
+ }
56
+
57
+ doBefore(context: MessageInterceptorContext, messages: GeneralMessage[]): void {
58
+ if (!this.meterManager.isEnabled()) {
59
+ return;
60
+ }
61
+ switch (context.getMessageHookPoints()) {
62
+ case MessageHookPoints.SEND:
63
+ context.putAttribute(MessageMeterInterceptor.SEND_STOPWATCH_KEY, Attribute.create(Date.now()));
64
+ break;
65
+ case MessageHookPoints.CONSUME: {
66
+ const consumerGroup = this.getConsumerGroup();
67
+ if (!consumerGroup) {
68
+ break;
69
+ }
70
+ const message = messages[0] as MetricMessage | undefined;
71
+ if (!message || !message.decodeTimestamp) {
72
+ break;
73
+ }
74
+ const latency = Date.now() - message.decodeTimestamp.getTime();
75
+ const attributes = this.#consumerAttributes(message.topic, consumerGroup);
76
+ this.meterManager.record(HistogramEnum.AWAIT_TIME, attributes, latency);
77
+ context.putAttribute(MessageMeterInterceptor.CONSUME_STOPWATCH_KEY, Attribute.create(Date.now()));
78
+ break;
79
+ }
80
+ default:
81
+ break;
82
+ }
83
+ }
84
+
85
+ doAfter(context: MessageInterceptorContext, messages: GeneralMessage[]): void {
86
+ if (!this.meterManager.isEnabled()) {
87
+ return;
88
+ }
89
+ const status = context.getStatus();
90
+ const invocationStatus = status === MessageHookPointsStatus.OK ? InvocationStatus.SUCCESS : InvocationStatus.FAILURE;
91
+ switch (context.getMessageHookPoints()) {
92
+ case MessageHookPoints.SEND: {
93
+ const attr = context.getAttribute(MessageMeterInterceptor.SEND_STOPWATCH_KEY);
94
+ if (!attr) {
95
+ break;
96
+ }
97
+ const message = messages[0] as MetricMessage | undefined;
98
+ if (!message) {
99
+ break;
100
+ }
101
+ const cost = Date.now() - attr.get();
102
+ const attributes: Attributes = {
103
+ [MetricLabels.TOPIC]: message.topic,
104
+ [MetricLabels.CLIENT_ID]: this.clientId,
105
+ [MetricLabels.INVOCATION_STATUS]: invocationStatus.name,
106
+ };
107
+ this.meterManager.record(HistogramEnum.SEND_COST_TIME, attributes, cost);
108
+ break;
109
+ }
110
+ case MessageHookPoints.RECEIVE: {
111
+ const consumerGroup = this.getConsumerGroup();
112
+ if (!consumerGroup) {
113
+ break;
114
+ }
115
+ const message = messages[0] as MetricMessage | undefined;
116
+ if (!message || !message.transportDeliveryTimestamp) {
117
+ break;
118
+ }
119
+ const latency = Date.now() - message.transportDeliveryTimestamp.getTime();
120
+ if (latency < 0) {
121
+ break;
122
+ }
123
+ const attributes = this.#consumerAttributes(message.topic, consumerGroup);
124
+ this.meterManager.record(HistogramEnum.DELIVERY_LATENCY, attributes, latency);
125
+ break;
126
+ }
127
+ case MessageHookPoints.CONSUME: {
128
+ const consumerGroup = this.getConsumerGroup();
129
+ if (!consumerGroup) {
130
+ break;
131
+ }
132
+ const attr = context.getAttribute(MessageMeterInterceptor.CONSUME_STOPWATCH_KEY);
133
+ if (!attr) {
134
+ break;
135
+ }
136
+ const message = messages[0] as MetricMessage | undefined;
137
+ if (!message) {
138
+ break;
139
+ }
140
+ const cost = Date.now() - attr.get();
141
+ const attributes: Attributes = {
142
+ [MetricLabels.TOPIC]: message.topic,
143
+ [MetricLabels.CLIENT_ID]: this.clientId,
144
+ [MetricLabels.CONSUMER_GROUP]: consumerGroup,
145
+ [MetricLabels.INVOCATION_STATUS]: invocationStatus.name,
146
+ };
147
+ this.meterManager.record(HistogramEnum.PROCESS_TIME, attributes, cost);
148
+ break;
149
+ }
150
+ default:
151
+ break;
152
+ }
153
+ }
154
+
155
+ #consumerAttributes(topic: string, consumerGroup: string): Attributes {
156
+ return {
157
+ [MetricLabels.TOPIC]: topic,
158
+ [MetricLabels.CLIENT_ID]: this.clientId,
159
+ [MetricLabels.CONSUMER_GROUP]: consumerGroup,
160
+ };
161
+ }
162
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ export * from './Attribute';
19
+ export * from './AttributeKey';
20
+ export * from './CompositedMessageInterceptor';
21
+ export * from './InflightRequestCountInterceptor';
22
+ export * from './MessageHookPoints';
23
+ export * from './MessageHookPointsStatus';
24
+ export * from './MessageInterceptor';
25
+ export * from './MessageInterceptorContext';
26
+ export * from './MessageInterceptorContextImpl';
27
+ export * from './MessageMeterInterceptor';
package/src/index.ts CHANGED
@@ -17,6 +17,7 @@
17
17
 
18
18
  export * from './consumer';
19
19
  export * from './exception';
20
+ export * from './hook';
20
21
  export * from './message';
21
22
  export * from './producer';
22
23
  export * from './retry';
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Attributes, Histogram, Meter } from '@opentelemetry/api';
19
+ import { MeterProvider as SdkMeterProvider } from '@opentelemetry/sdk-metrics';
20
+ import { Endpoints } from '../route';
21
+ import { HistogramEnum } from './HistogramEnum';
22
+ import { Metric } from './Metric';
23
+
24
+ /**
25
+ * Wraps an OpenTelemetry {@link Meter} and records the four RocketMQ histograms.
26
+ * When metrics are disabled it is a no-op instance, mirroring
27
+ * org.apache.rocketmq.client.java.metrics.ClientMeter.
28
+ */
29
+ export class ClientMeter {
30
+ readonly enabled: boolean;
31
+ private readonly meter?: Meter;
32
+ private readonly endpoints?: Endpoints;
33
+ private readonly provider?: SdkMeterProvider;
34
+ private readonly histogramMap = new Map<HistogramEnum, Histogram>();
35
+
36
+ constructor(meter: Meter | null, endpoints: Endpoints | null, provider: SdkMeterProvider | null) {
37
+ this.enabled = meter != null && endpoints != null && provider != null;
38
+ this.meter = meter ?? undefined;
39
+ this.endpoints = endpoints ?? undefined;
40
+ this.provider = provider ?? undefined;
41
+ }
42
+
43
+ static disabledInstance(): ClientMeter {
44
+ return new ClientMeter(null, null, null);
45
+ }
46
+
47
+ record(histogramEnum: HistogramEnum, attributes: Attributes, value: number) {
48
+ if (!this.enabled || !this.meter) {
49
+ return;
50
+ }
51
+ let histogram = this.histogramMap.get(histogramEnum);
52
+ if (!histogram) {
53
+ histogram = this.meter.createHistogram(histogramEnum);
54
+ this.histogramMap.set(histogramEnum, histogram);
55
+ }
56
+ histogram.record(value, attributes);
57
+ }
58
+
59
+ async shutdown() {
60
+ if (!this.enabled || !this.provider) {
61
+ return;
62
+ }
63
+ try {
64
+ await this.provider.shutdown();
65
+ } catch (t) {
66
+ // best-effort shutdown, ignore
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Returns true if the supplied metric switch is already satisfied by this
72
+ * meter (so a rebuild is unnecessary), mirroring ClientMeter#satisfy.
73
+ */
74
+ satisfy(metric: Metric): boolean {
75
+ if (this.enabled && metric.on && this.endpoints != null && metric.endpoints != null
76
+ && this.endpoints.equals(metric.endpoints)) {
77
+ return true;
78
+ }
79
+ return !this.enabled && !metric.on;
80
+ }
81
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Attributes, Meter } from '@opentelemetry/api';
19
+ import {
20
+ MeterProvider as SdkMeterProvider,
21
+ PeriodicExportingMetricReader,
22
+ View,
23
+ } from '@opentelemetry/sdk-metrics';
24
+ import { Resource } from '@opentelemetry/resources';
25
+ import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
26
+ import { ChannelCredentials, Metadata } from '@grpc/grpc-js';
27
+ import { ILogger } from '../client/Logger';
28
+ import { ClientMeter } from './ClientMeter';
29
+ import { GaugeObserver } from './GaugeObserver';
30
+ import { EmptyGaugeObserver } from './EmptyGaugeObserver';
31
+ import { HistogramEnum, buildHistogramView } from './HistogramEnum';
32
+ import { Metric } from './Metric';
33
+
34
+ const METRIC_EXPORTER_RPC_TIMEOUT = 5000;
35
+ const METRIC_READER_INTERVAL = 60000;
36
+ const METRIC_INSTRUMENTATION_NAME = 'org.apache.rocketmq.message';
37
+
38
+ /**
39
+ * Owns the OpenTelemetry metric pipeline for a single client. On every settings
40
+ * command it lazily (re)builds an SdkMeterProvider that exports the four
41
+ * RocketMQ histograms plus the consumer gauges to the broker-supplied metric
42
+ * endpoints over OTLP/gRPC, mirroring
43
+ * org.apache.rocketmq.client.java.metrics.ClientMeterManager.
44
+ */
45
+ export class ClientMeterManager {
46
+ private readonly clientId: string;
47
+ private readonly metadataProvider: () => Metadata;
48
+ private readonly logger: ILogger;
49
+ private clientMeter: ClientMeter;
50
+ private gaugeObserver: GaugeObserver = EmptyGaugeObserver.EMPTY;
51
+
52
+ constructor(clientId: string, metadataProvider: () => Metadata, logger: ILogger) {
53
+ this.clientId = clientId;
54
+ this.metadataProvider = metadataProvider;
55
+ this.logger = logger;
56
+ this.clientMeter = ClientMeter.disabledInstance();
57
+ }
58
+
59
+ setGaugeObserver(gaugeObserver: GaugeObserver) {
60
+ this.gaugeObserver = gaugeObserver;
61
+ }
62
+
63
+ record(histogramEnum: HistogramEnum, attributes: Attributes, value: number) {
64
+ this.clientMeter.record(histogramEnum, attributes, value);
65
+ }
66
+
67
+ isEnabled(): boolean {
68
+ return this.clientMeter.enabled;
69
+ }
70
+
71
+ async shutdown() {
72
+ await this.clientMeter.shutdown();
73
+ }
74
+
75
+ async reset(metric: Metric): Promise<void> {
76
+ try {
77
+ if (this.clientMeter.satisfy(metric)) {
78
+ this.logger.info('Metric settings is satisfied by the current message meter, metric=%j, clientId=%s',
79
+ metric, this.clientId);
80
+ return;
81
+ }
82
+ if (!metric.on || !metric.endpoints) {
83
+ this.logger.info('Metric is off, clientId=%s', this.clientId);
84
+ await this.clientMeter.shutdown();
85
+ this.clientMeter = ClientMeter.disabledInstance();
86
+ return;
87
+ }
88
+ const endpoints = metric.endpoints;
89
+ // Use the first address as the OTLP/gRPC target. The exporter's URL is
90
+ // normalized to "host:port" internally, which gRPC-js resolves through
91
+ // its default DNS resolver (a single IP works fine; the custom `ip`
92
+ // resolver is used for the primary RPC channels).
93
+ const address = endpoints.addressesList[0];
94
+ const url = `http://${address.host}:${address.port}`;
95
+ const exporter = new OTLPMetricExporter({
96
+ url,
97
+ credentials: ChannelCredentials.createInsecure(),
98
+ timeoutMillis: METRIC_EXPORTER_RPC_TIMEOUT,
99
+ // Per-request signing mirrors the Java client's AuthInterceptor. The
100
+ // d.ts types this field as `Metadata`, but the runtime (and the
101
+ // exporter's own merge logic in otlp-grpc-exporter-base) expects a
102
+ // function returning freshly-signed Metadata.
103
+ metadata: (() => this.metadataProvider()) as unknown as Metadata,
104
+ });
105
+
106
+ const reader = new PeriodicExportingMetricReader({
107
+ exporter,
108
+ exportIntervalMillis: METRIC_READER_INTERVAL,
109
+ exportTimeoutMillis: METRIC_EXPORTER_RPC_TIMEOUT,
110
+ });
111
+
112
+ const views: View[] = [
113
+ new View(buildHistogramView(HistogramEnum.SEND_COST_TIME)),
114
+ new View(buildHistogramView(HistogramEnum.DELIVERY_LATENCY)),
115
+ new View(buildHistogramView(HistogramEnum.AWAIT_TIME)),
116
+ new View(buildHistogramView(HistogramEnum.PROCESS_TIME)),
117
+ ];
118
+
119
+ const provider: SdkMeterProvider = new SdkMeterProvider({
120
+ resource: Resource.empty(),
121
+ readers: [ reader ],
122
+ views,
123
+ });
124
+
125
+ const meter: Meter = provider.getMeter(METRIC_INSTRUMENTATION_NAME);
126
+
127
+ const existedClientMeter = this.clientMeter;
128
+ this.clientMeter = new ClientMeter(meter, endpoints, provider);
129
+ await existedClientMeter.shutdown();
130
+ this.logger.info('Metrics is on, endpoints=%s, clientId=%s', endpoints, this.clientId);
131
+
132
+ const gauges = this.gaugeObserver.getGauges();
133
+ for (const gauge of gauges) {
134
+ meter.createObservableGauge(gauge).addCallback(observableResult => {
135
+ const values = this.gaugeObserver.getValues(gauge);
136
+ for (const [ attributes, value ] of values) {
137
+ observableResult.observe(value, attributes);
138
+ }
139
+ });
140
+ }
141
+ } catch (t) {
142
+ this.logger.error('Exception raised when resetting message meter, clientId=%s, error=%s', this.clientId, t);
143
+ }
144
+ }
145
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Licensed to the Apache Software Foundation (ASF) under one or more
3
+ * contributor license agreements. See the NOTICE file distributed with
4
+ * this work for additional information regarding copyright ownership.
5
+ * The ASF licenses this file to You under the Apache License, Version 2.0
6
+ * (the "License"); you may not use this file except in compliance with
7
+ * the License. You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { Attributes } from '@opentelemetry/api';
19
+ import { GaugeEnum } from './GaugeEnum';
20
+ import { GaugeObserver } from './GaugeObserver';
21
+
22
+ /**
23
+ * Default no-op gauge observer used before a consumer registers a real one,
24
+ * mirroring org.apache.rocketmq.client.java.metrics.EmptyGaugeObserver.
25
+ */
26
+ export class EmptyGaugeObserver implements GaugeObserver {
27
+ static readonly EMPTY: EmptyGaugeObserver = new EmptyGaugeObserver();
28
+
29
+ getGauges(): GaugeEnum[] {
30
+ return [];
31
+ }
32
+
33
+ getValues(): Map<Attributes, number> {
34
+ return new Map();
35
+ }
36
+ }