All files / core/blong-gogo/src/adapter/server kafka.ts

57.83% Statements 214/370
78.94% Branches 15/19
50% Functions 5/10
57.83% Lines 214/370

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 3711x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                           1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x 1x                     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                                                                                                                                                                 1x 1x  
import {adapter, type IMeta} from '@feasibleone/blong/types';
import Kafka, {type Message} from 'node-rdkafka';
import {Duplex} from 'stream';
 
type KafkaConfig = ConstructorParameters<typeof Kafka.KafkaConsumer>[0];
 
type CodecInstance = {
    encode: (...args: unknown[]) => Promise<string | Buffer<ArrayBufferLike>>;
    decode: (...args: unknown[]) => Promise<object[]>;
};
 
export interface IConfig {
    connection: KafkaConfig;
    consume: {
        topics: string[];
        groupId: string;
    };
    codec?: {
        new (config: object): CodecInstance;
    };
    /**
     * Operation mode.
     * - `'stream'` (default): a produce/consume message adapter — every triple
     *   is routed through the Kafka stream (the request is encoded and produced
     *   to `consume.topics`, the response is consumed + decoded). This is the
     *   original design for message round-trips.
     * - `'admin'`: an introspection adapter — triples are routed to `exec`
     *   (like the API adapters: `super.connect()` → `handle()` → `exec`), so
     *   `{ns}.topic.list` (broker metadata) and `{ns}.topic.find` (message
     *   reads via one-off consumers) are reachable. No produce/consume stream.
     */
    mode?: 'stream' | 'admin';
}
 
export default adapter<IConfig>(() => {
    let stream: Duplex | null = null;
    let codec: CodecInstance | null = null;
    let producerStream: ReturnType<typeof Kafka.Producer.createWriteStream> | null = null;
    let consumerStream:
        | (ReturnType<typeof Kafka.KafkaConsumer.createReadStream> & {
              consumer: {
                  isConnected(): boolean;
                  once(event: 'ready', cb: () => void): void;
                  assignments(): {partition: number; topic: string; offset: number}[];
                  getMetadata(
                      opts: {timeout: number},
                      cb: (
                          err: Error | null,
                          data?: {topics?: Array<{name: string; partitions: unknown[]}>},
                      ) => void,
                  ): void;
              };
          })
        | null = null;
 
    return {
        activation: {
            default: {
                type: 'kafka',
                connection: {
                    'client.id': 'blong',
                    'security.protocol': 'sasl_plaintext',
                    'sasl.mechanism': 'SCRAM-SHA-256',
                },
            },
        },
 
        async start() {
            const result = await super.start();
 
            const isAdmin = this.config.mode === 'admin';
            // The codec encodes/decodes the Kafka stream message format. Admin
            // (introspection) mode routes triples to `exec` (plain object
            // responses), so the codec must NOT be applied there — a stream
            // codec would try `msg.value.toString()` on the exec result.
            if (this.config.codec && !isAdmin) {
                codec = new this.config.codec({});
                this.encode = (...params) => codec!.encode(...params);
                this.decode = (...params) => codec!.decode(...params);
            } else {
                codec = null;
            }
 
            const groupId = this.config.consume.groupId;
            const startedAt = Date.now();
            const consumerConfig = {
                ...this.config.connection,
                'group.id': groupId,
            };
            this.log?.info?.(
                {
                    groupId,
                    topics: this.config.consume.topics,
                    sessionTimeoutMs: consumerConfig['session.timeout.ms'],
                    broker: consumerConfig['metadata.broker.list'],
                },
                'kafka consumer creating',
            );
 
            consumerStream = Kafka.KafkaConsumer.createReadStream(
                consumerConfig,
                {
                    'auto.offset.reset': 'earliest',
                },
                {topics: this.config.consume.topics},
            ) as typeof consumerStream;
 
            // Wait for consumer to connect and receive partition assignments.
            // node-rdkafka group rebalance can take up to a few seconds after 'ready'.
            await new Promise<void>((resolve, reject) => {
                let poll: ReturnType<typeof setInterval> | null = null;
                let safety: ReturnType<typeof setTimeout> | null = null;
                const cleanup = () => {
                    if (poll) clearInterval(poll);
                    if (safety) clearTimeout(safety);
                    poll = null;
                    safety = null;
                };
                const startPolling = () => {
                    poll = setInterval(() => {
                        if (consumerStream!.consumer.assignments().length > 0) {
                            cleanup();
                            this.log?.info?.(
                                {groupId, elapsedMs: Date.now() - startedAt},
                                'kafka consumer assigned',
                            );
                            resolve();
                        }
                    }, 200);
                    safety = setTimeout(() => {
                        cleanup();
                        this.log?.warn?.(
                            {
                                groupId,
                                elapsedMs: Date.now() - startedAt,
                                hint: 'stale group members from an earlier abrupt shutdown keep the rebalance waiting up to session.timeout.ms',
                            },
                            'kafka consumer assignment timed out',
                        );
                        // Best-effort graceful close BEFORE failing start: a
                        // consumer that joined the group but never got an
                        // assignment would otherwise linger as a stale group
                        // member (no LeaveGroup), blocking the NEXT rebalance
                        // for up to session.timeout.ms too. destroy() →
                        // close() → disconnect() sends LeaveGroup.
                        try {
                            consumerStream?.destroy();
                        } catch {
                            // ignore — the process is already failing start
                        }
                        reject(new Error('Kafka assignment timeout'));
                    }, 30000);
                };
                if (consumerStream!.consumer.isConnected()) {
                    this.log?.info?.({groupId}, 'kafka consumer already connected');
                    startPolling();
                } else {
                    this.log?.info?.({groupId}, 'kafka consumer connecting, waiting for ready');
                    consumerStream!.consumer.once('ready', () => {
                        this.log?.info?.(
                            {groupId, elapsedMs: Date.now() - startedAt},
                            'kafka consumer ready',
                        );
                        startPolling();
                    });
                }
            });
 
            if (this.config.mode === 'admin') {
                // Admin/introspection mode — route triples to `exec`
                // (`super.connect()` → `handle()` → `findHandler(method) ||
                // imported['exec']`). The consumer stays connected for broker
                // metadata (`{ns}.topic.list` uses `getMetadata`); the
                // produce/consume Duplex is not built and no messages are
                // consumed by this adapter instance.
                super.connect();
            } else {
                producerStream = Kafka.Producer.createWriteStream(
                    {
                        ...this.config.connection,
                    },
                    {},
                    {
                        objectMode: true,
                    },
                );

                // Build a custom Duplex that writes to the Kafka producer and
                // receives messages from the Kafka consumer via 'data' events.
                // Duplex.from({readable, writable}) is not used because it does
                // not reliably forward object-mode events from the inner readable.
                stream = new Duplex({objectMode: true, read() {}});
                stream.write = (chunk, ...args) =>
                    (producerStream!.write as (...a: unknown[]) => boolean)(chunk, ...args);

                consumerStream!.on('data', msg => stream?.push(msg));
                consumerStream!.on('end', () => stream?.push(null));
                consumerStream!.on('error', err => stream?.destroy(err as Error));

                super.connect(stream);
            }
 
            return result;
        },
 
        async stop(...params: unknown[]) {
            const groupId = this.config.consume.groupId;
            const stopStartedAt = Date.now();
            this.log?.info?.({groupId}, 'kafka adapter stop');
            const awaitClose = (
                s: {once(e: 'close', cb: () => void): void} | null,
                disconnect: () => void,
                ms: number,
            ) =>
                !s
                    ? Promise.resolve()
                    : new Promise<void>(resolve => {
                          const t = setTimeout(() => {
                              this.log?.warn?.(
                                  {
                                      groupId,
                                      waitMs: ms,
                                      elapsedMs: Date.now() - stopStartedAt,
                                      hint: 'consumer/producer did not emit close — the group member was not gracefully removed',
                                  },
                                  'kafka close timed out',
                              );
                              resolve();
                          }, ms);
                          s.once('close', () => {
                              clearTimeout(t);
                              this.log?.info?.(
                                  {
                                      groupId,
                                      elapsedMs: Date.now() - stopStartedAt,
                                  },
                                  'kafka consumer/producer closed (LeaveGroup sent)',
                              );
                              resolve();
                          });
                          disconnect();
                      });
 
            let result;
            try {
                stream?.destroy();
                // consumerStream.destroy() → close() → consumer.disconnect() → emits 'close'
                // producerStream.close()   →           producer.disconnect() → emits 'close'
                // Both must complete so rdkafka uv handles are released and the process exits.
                await Promise.all([
                    awaitClose(consumerStream, () => consumerStream?.destroy(), 20000),
                    awaitClose(
                        producerStream as unknown as Parameters<typeof awaitClose>[0],
                        () => (producerStream as unknown as {close(): void} | null)?.close(),
                        20000,
                    ),
                ]);
                this.log?.info?.(
                    {groupId, elapsedMs: Date.now() - stopStartedAt},
                    'kafka adapter stop complete',
                );
            } finally {
                stream = null;
                codec = null;
                consumerStream = null;
                producerStream = null;
                result = await super.stop(...params);
            }
            return result;
        },
 
        async exec(
            params: Record<string, unknown>,
            $meta: IMeta,
        ): Promise<unknown> {
            const {method} = $meta;
            const [, object, operation] = method!.split('.');
            if (object === 'topic') {
                switch (operation) {
                    case 'list': {
                        // `{ns}.topic.list` — enumerate topics from broker metadata
                        if (!consumerStream) {
                            throw new Error('Kafka consumer not connected');
                        }
                        const metadata = await new Promise<{
                            topics: Array<{name: string; partitions: unknown[]}>;
                        }>((resolve, reject) => {
                            consumerStream!.consumer.getMetadata(
                                {timeout: 5000, allTopics: true},
                                (err, data) => (err ? reject(err) : resolve(data ?? {topics: []})),
                            );
                        });
                        return {
                            items: (metadata.topics ?? [])
                                .filter(t => !t.name.startsWith('__'))
                                .map(t => ({
                                    topic: t.name,
                                    partitionCount: t.partitions?.length ?? 0,
                                })),
                        };
                    }
                    case 'find': {
                        // `{ns}.topic.find` — read a batch of messages from a topic.
                        // A fresh consumer group with `auto.offset.reset: earliest`
                        // reads existing messages from the beginning (exploration);
                        // partitions are surfaced as message metadata, not tree nodes.
                        const topic = params.topic as string;
                        const limit = (params.limit as number) ?? 50;
                        if (!topic) {
                            throw new Error('Missing topic param');
                        }
                        const consumer = new Kafka.KafkaConsumer(
                            {
                                ...this.config.connection,
                                'group.id': `blong-commander-${Date.now()}`,
                            },
                            {'auto.offset.reset': 'earliest'},
                        );
                        // A fresh group must complete the rebalance (group join +
                        // partition assignment) before the first consume returns.
                        consumer.setDefaultConsumeTimeout(3000);
                        // Always RESOLVE to a (possibly empty) batch — a rebalance
                        // stall or broker hiccup must surface as an empty topic, not
                        // as a malformed/empty RPC response ("JSON RPC response
                        // without response and error").
                        const messages = await new Promise<Message[] | undefined>(resolve => {
                            const timer = setTimeout(() => {
                                try {
                                    consumer.disconnect();
                                } catch {
                                    // ignore
                                }
                                resolve(undefined);
                            }, 15000);
                            const done = (msgs: Message[] | undefined) => {
                                clearTimeout(timer);
                                try {
                                    consumer.disconnect();
                                } catch {
                                    // ignore
                                }
                                resolve(msgs);
                            };
                            consumer.on('ready', () => {
                                consumer.subscribe([topic]);
                                consumer.consume(limit, (err, msgs) => {
                                    if (err) return done(undefined);
                                    done(msgs);
                                });
                            });
                            consumer.on('event.error', () => done(undefined));
                            consumer.connect();
                        });
                        return {
                            items: (messages ?? []).map(m => ({
                                topic: m.topic,
                                partition: m.partition,
                                offset: m.offset,
                                key: m.key?.toString(),
                                value: m.value?.toString(),
                                timestamp: m.timestamp,
                            })),
                        };
                    }
                }
            }
            throw new Error(`Unknown kafka operation: ${object}.${operation}`);
        },
    };
});