kafka-crab-js 2.0.0 → 2.1.0-alpha.1

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
@@ -43,17 +43,6 @@ This major version includes important breaking changes that improve API consiste
43
43
  - Better TypeScript typing throughout the codebase
44
44
  - Removed redundant validation functions for cleaner code
45
45
 
46
- ### Migration Guide
47
-
48
- - **No API changes required** - all public interfaces remain the same
49
- - **Stream memory management** - streams now automatically clean up resources
50
- - **Error handling** - streams will properly terminate on errors (existing error handling code still works)
51
- - **Performance** - simplified timeout logic may provide marginal performance improvements
52
-
53
- ---
54
-
55
- ## What's New in Version 2.0.0
56
-
57
46
  ### Major Updates:
58
47
 
59
48
  1. **Performance Benchmark Suite**:
@@ -88,24 +77,29 @@ This major version includes important breaking changes that improve API consiste
88
77
  - Added support for benchmark directory linting and formatting
89
78
  - Improved development workflow with better error handling rules
90
79
 
91
- ### Previous Version (1.9.0) Updates:
92
- 7. **Consumer Topic Creation Control**:
80
+ 7. **Consumer Topic Creation Control** (v1.9.0):
93
81
  - Added fine-grained control over consumer topic creation behavior
94
82
  - Enhanced consistency in topic management and cleanup processes
95
83
  - Improved handling of topic creation inconsistencies during consumer operations
96
84
 
97
- 8. **Enhanced Manual Commit Testing**:
85
+ 8. **Enhanced Manual Commit Testing** (v1.9.0):
98
86
  - Consolidated manual commit tests for better reliability and coverage
99
87
  - Added comprehensive integration tests with PostRebalance event handling
100
88
  - Tests now verify offset persistence across consumer restarts and batch processing
101
89
 
102
- ### Previous Version (1.8.0) Breaking Changes:
103
- 9. **Async Consumer Commit**:
90
+ 9. **Async Consumer Commit** (v1.8.0 - BREAKING):
104
91
  - **BREAKING**: The `consumer.commit()` method is now async and must be awaited
105
92
  - **Before**: `consumer.commit(topic, partition, offset, 'Sync')`
106
93
  - **After**: `await consumer.commit(topic, partition, offset, 'Sync')`
107
94
  - This change improves performance by using `spawn_blocking` for non-blocking operations
108
95
 
96
+ ### Migration Guide
97
+
98
+ - **No API changes required** - all public interfaces remain the same
99
+ - **Stream memory management** - streams now automatically clean up resources
100
+ - **Error handling** - streams will properly terminate on errors (existing error handling code still works)
101
+ - **Performance** - simplified timeout logic may provide marginal performance improvements
102
+
109
103
  ---
110
104
 
111
105
  ## Features
@@ -134,6 +128,7 @@ This major version includes important breaking changes that improve API consiste
134
128
  8. [Best Practices](#best-practices)
135
129
  9. [Contributing](#contributing)
136
130
  10. [License](#license)
131
+ 11. [OpenTelemetry Instrumentation](#opentelemetry-instrumentation)
137
132
 
138
133
  ## Installation
139
134
 
@@ -249,12 +244,12 @@ const kafkaClient = new KafkaClient({
249
244
  brokerAddressFamily: 'v4',
250
245
  });
251
246
 
252
- // Stream consumer with custom ReadableOptions (v1.10.0+)
247
+ // Stream consumer with custom ReadableOptions (v2.0.0+)
253
248
  const kafkaStream = kafkaClient.createStreamConsumer({
254
249
  groupId: `my-group-id`,
255
250
  enableAutoCommit: true,
256
251
  }, {
257
- objectMode: true, // Default in v1.10.0+
252
+ objectMode: true, // Default in v2.0.0+
258
253
  highWaterMark: 1024,
259
254
  encoding: null
260
255
  });
@@ -464,8 +459,6 @@ You can find some examples on the [example](https://github.com/flash-tecnologia/
464
459
 
465
460
  ## Configuration
466
461
 
467
- ### Configuration properties
468
-
469
462
  ### KafkaConfiguration
470
463
 
471
464
  | Property | Type | Default | Description |
@@ -475,7 +468,8 @@ You can find some examples on the [example](https://github.com/flash-tecnologia/
475
468
  | `securityProtocol` | `SecurityProtocol` || Security protocol to use (PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL) |
476
469
  | `logLevel` | `string` | `info` | Log level for the client |
477
470
  | `brokerAddressFamily` | `string` | `"v4"` | Address family to use for the connection (v4, v6) |
478
- | `configuration` | `Record<string, any>` | `{}` | Additional configuration options for the client. **v1.10.0+**: Now supports any value type (string, number, boolean, object) |
471
+ | `configuration` | `Record<string, any>` | `{}` | Additional configuration options for the client. **v2.0.0+**: Now supports any value type (string, number, boolean, object) |
472
+ | `otel` | `KafkaOtelInstrumentationConfig \| false` | `undefined` | Enable and configure OpenTelemetry instrumentation (see [OpenTelemetry Instrumentation](#opentelemetry-instrumentation)) |
479
473
 
480
474
  ### ConsumerConfiguration
481
475
 
@@ -502,17 +496,41 @@ You can find some examples on the [example](https://github.com/flash-tecnologia/
502
496
  | `topic` | `string` || Topic name |
503
497
  | `allOffsets` | `OffsetModel` || Offset configuration for all partitions |
504
498
  | `partitionOffset` | `Array<PartitionOffset>` || Per-partition offset configuration |
505
- | `createTopic` | `boolean` | `false` | **v2.0.x+**: Create topic if it doesn't exist |
506
- | `numPartitions` | `number` | `1` | **v2.0.x+**: Number of partitions when creating topic |
507
- | `replicas` | `number` | `1` | **v2.0.x+**: Number of replicas when creating topic |
499
+ | `createTopic` | `boolean` | `false` | **v2.0.0+**: Create topic if it doesn't exist |
500
+ | `numPartitions` | `number` | `1` | **v2.0.0+**: Number of partitions when creating topic |
501
+ | `replicas` | `number` | `1` | **v2.0.0+**: Number of replicas when creating topic |
508
502
 
509
503
  You can see the available options here: [librdkafka](https://docs.confluent.io/platform/current/clients/librdkafka/html/md_CONFIGURATION.html).
510
504
 
505
+ ### OpenTelemetry Configuration
506
+
507
+ OpenTelemetry is enabled by default when the `otel` field is omitted or set to an object. Set `otel: false` to disable instrumentation entirely.
508
+
509
+ ```ts
510
+ const client = new KafkaClient({
511
+ brokers: 'localhost:29092',
512
+ clientId: 'payments-service',
513
+ otel: {
514
+ serviceName: 'payments-api',
515
+ ignoreTopics: topic => topic.startsWith('internal.'),
516
+ messageHook: (span, message) => {
517
+ span.setAttribute('app.message.key', message.key?.toString('utf8'))
518
+ },
519
+ },
520
+ })
521
+ ```
522
+
523
+ When instrumentation is active:
524
+
525
+ - Producer `send` calls automatically propagate the active span context via Kafka headers while preserving custom headers and their Buffer/string types.
526
+ - Consumer `recv`, `recvBatch`, and stream consumers generate spans that capture consumer group, topic, partition, offset, and batch size.
527
+ - Hooks registered through `messageHook` and `producerHook` execute within the active span context so that additional attributes/events can be attached safely.
528
+
511
529
  ## Performance Benchmarks
512
530
 
513
531
  ### Running Benchmarks
514
532
 
515
- kafka-crab-js v1.10.0+ includes a comprehensive benchmark suite to compare performance against other popular Kafka clients:
533
+ kafka-crab-js v2.0.0+ includes a comprehensive benchmark suite to compare performance against other popular Kafka clients:
516
534
 
517
535
  ```bash
518
536
  # Set up benchmark environment (requires Kafka running locally)
@@ -582,7 +600,7 @@ const maxBytes = 200 // Maximum message size
582
600
  - Monitor and tune consumer group performance
583
601
  - Leverage the benchmark suite to optimize your specific use case
584
602
 
585
- ### Configuration (v1.10.0+)
603
+ ### Configuration (v2.0.0+)
586
604
  - Use the flexible configuration system with proper data types:
587
605
  ```javascript
588
606
  const config = {
@@ -599,7 +617,7 @@ const maxBytes = 200 // Maximum message size
599
617
  - Handle message ordering when required
600
618
  - Use topic creation options for better topic management
601
619
 
602
- ### Stream Processing (v1.10.0+)
620
+ ### Stream Processing (v2.0.0+)
603
621
  - Configure appropriate `ReadableOptions` for your use case
604
622
  - Use `objectMode: true` for structured message processing
605
623
  - Set appropriate `highWaterMark` based on memory constraints
@@ -633,6 +651,60 @@ npx tsx benchmark/utils/setup.ts
633
651
  npx tsx benchmark/consumer.ts
634
652
  ```
635
653
 
654
+ ## OpenTelemetry Instrumentation
655
+
656
+ Kafka Crab JS offers turnkey tracing for Kafka workloads:
657
+
658
+ - **Seamless propagation** – Producer instrumentation injects `traceparent`/`tracestate` into Kafka headers while retaining any existing headers (including `Buffer` values) so downstream systems continue to see custom metadata.
659
+ - **Consumer & stream coverage** – Standard consumers, batch consumers, and `createStreamConsumer` streams emit spans that include consumer group, topic, partition, offset, and batch size semantics.
660
+ - **Hook-friendly spans** – Both `messageHook` and `producerHook` callbacks run inside the active span context, simplifying attribute decoration or error handling.
661
+ - **Header normalization helpers** – The runtime automatically normalizes mixed header carriers to Buffers when talking to the native binding, removing the need for manual conversions.
662
+
663
+ ### Minimal Setup Example
664
+
665
+ ```ts
666
+ import { KafkaClient } from 'kafka-crab-js'
667
+ import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
668
+ import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'
669
+ import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'
670
+ import { context } from '@opentelemetry/api'
671
+
672
+ const provider = new NodeTracerProvider()
673
+ provider.addSpanProcessor(new SimpleSpanProcessor(exporter))
674
+ provider.register()
675
+
676
+ context.setGlobalContextManager(new AsyncHooksContextManager().enable())
677
+
678
+ const client = new KafkaClient({
679
+ brokers: 'localhost:29092',
680
+ clientId: 'orders-api',
681
+ otel: {
682
+ serviceName: 'orders-service',
683
+ producerHook: span => span.setAttribute('messaging.client.kind', 'producer'),
684
+ },
685
+ })
686
+
687
+ const producer = client.createProducer()
688
+ await producer.send({
689
+ topic: 'orders',
690
+ messages: [{
691
+ payload: Buffer.from(JSON.stringify({ orderId: '123' })),
692
+ headers: { 'custom-header': 'foo' },
693
+ }],
694
+ })
695
+
696
+ const consumer = client.createStreamConsumer({
697
+ groupId: 'orders-consumer',
698
+ enableAutoCommit: false,
699
+ })
700
+
701
+ consumer.on('data', message => {
702
+ console.log(message.headers?.['custom-header']?.toString())
703
+ })
704
+ ```
705
+
706
+ Set `otel: false` in the client configuration to opt-out.
707
+
636
708
  ## License
637
709
 
638
710
  This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.