UNPKG

@nestjs/microservices

Version:

Microservices for NestJS: message and event handlers over Kafka, RabbitMQ, NATS, Redis, MQTT, gRPC or TCP.

123 lines (122 loc) • 7.1 kB
import { KafkaContext } from '../ctx-host/index.js'; import { KafkaStatus } from '../events/index.js'; import { BrokersFunction, Consumer, EachMessagePayload, IHeaders, Kafka, Message, Producer, RecordMetadata } from '../external/kafka.interface.js'; import { KafkaParser } from '../helpers/index.js'; import { KafkaOptions, MessageHandler, OutgoingResponse, ReadPacket, TransportId } from '../interfaces/index.js'; import { Server } from './server.js'; import { Logger } from '@nestjs/common'; /** * @publicApi */ export declare class ServerKafka extends Server<never, KafkaStatus> { protected readonly options: Required<KafkaOptions>['options']; readonly propagatesEventHandlerErrors = true; transportId: TransportId; protected logger: Logger; protected client: Kafka | null; protected consumer: Consumer | null; protected producer: Producer | null; protected parser: KafkaParser | null; protected brokers: string[] | BrokersFunction; protected clientId: string; protected groupId: string; constructor(options: Required<KafkaOptions>['options']); addHandler(pattern: any, callback: MessageHandler, isEventHandler?: boolean, extras?: Record<string, any>): void; listen(callback: (err?: unknown, ...optionalParams: unknown[]) => void): Promise<void>; close(): Promise<void>; start(callback: () => void): Promise<void>; protected registerConsumerEventListeners(): void; protected registerProducerEventListeners(): void; createClient<T = any>(): Promise<T>; bindEvents(consumer: Consumer): Promise<void>; getHandlerByPattern(pattern: string): MessageHandler | null; /** * A regex pattern also matches the topic this server replies on * ("orders.created.reply"), so the server consumes its own replies. Those * are skipped unless the regex that matches them targets reply topics only. */ private isOwnReply; /** * Whether a request may be answered on the reply topic it names. A reply is * published with the credentials of this server and has no envelope, so on * a topic this server handles it would run that topic's handlers as an * event (unless it is skipped as one of the server's own replies, see * `isOwnReply`). kafkajs also keeps state per topic in plain objects, which * a topic named after an `Object.prototype` property (`__proto__`) reaches * through their prototype. */ protected canReplyOn(replyTopic: string, correlationId: unknown): boolean; private isPatternMatch; getMessageHandler(): (payload: EachMessagePayload) => Promise<any>; /** * Returns what the `eachMessage` callback rejects with when handling a * message failed with `err`. * * kafkajs delivers a message again when its handler rejects, and restarts * the consumer once the retries are exhausted, except for the errors it * takes for a bug in its own code: one message failing with one of those * would leave the consumer stopped, for every topic. An exception filter * that throws (as one written for HTTP does when given an RPC context) or * that passes on the handler's own error rejects with such an error, so it * reaches kafkajs as a plain error with the same message and stack, and the * original error as its cause. */ private toRetriableError; getPublisher(replyTopic: string, replyPartition: string, correlationId: string, context: KafkaContext): (data: any) => Promise<RecordMetadata[]>; /** * Handles a message received by the consumer. * * A message with the `kafka_correlationId` and `kafka_replyTopic` headers, * which `ClientKafka#send()` adds, is a request: what its handler responds * with, an error included, is published to the reply topic. Any other * message is handled as an event (see `handleEvent`), also when its * handler is a `@MessagePattern()` one, so that such handlers can consume * topics written by producers that do not add these headers. The server's * own replies that a regex pattern matches are skipped (see `isOwnReply`). */ handleMessage(payload: EachMessagePayload): Promise<any>; /** * Reads the packet metadata off the headers of a message as the broker * delivered them, before the parser decodes them: every header with a * single value that is UTF-8 text. A repeated header (an array) or one with * binary content has no `PacketMetadata` form. */ protected readMetadata(headers: IHeaders | undefined): import("../interfaces/packet.interface.js").PacketMetadata | undefined; protected shouldAnswerRejectedRequest(err: unknown): boolean; unwrap<T>(): T; on<EventKey extends string | number | symbol = string | number | symbol, EventCallback = any>(event: EventKey, callback: EventCallback): void; /** * Subscribes to the response of a request and settles once it emits, fails * or completes. A retriable exception that comes before any value rejects, * which makes kafkajs deliver the message again; otherwise it resolves with * the stream to reply with. * * That stream is subscribed to after the response, so it replays what the * response emitted until then, once. Later values are only passed on: a * long stream is not kept in memory until it completes. */ private combineStreamsAndThrowIfRetriable; sendMessage(message: OutgoingResponse, replyTopic: string, replyPartition: string | undefined | null, correlationId: string, context: KafkaContext): Promise<RecordMetadata[]>; assignIsDisposedHeader(outgoingResponse: OutgoingResponse, outgoingMessage: Message): void; assignErrorHeader(outgoingResponse: OutgoingResponse, outgoingMessage: Message): void; assignCorrelationIdHeader(correlationId: string, outgoingMessage: Message): void; assignReplyPartition(replyPartition: string | null | undefined, outgoingMessage: Message): void; /** * Handles a message as an event: one for an `@EventPattern()` handler, or * one without the reply headers (see `handleMessage`). * * The returned promise settles once the stream the handler returns * completes, and kafkajs only then moves on to the next message of the * partition, so a handler whose stream does not complete holds the * partition. A handler that fails (as when a guard or a pipe rejects the * message) rejects into kafkajs, which does not commit the message and * delivers it again: it retries it, and once its retries are exhausted it * restarts the consumer from the last committed offset. Handlers of topics * that other producers write to should complete their streams, and should * not fail on messages they cannot process unless these are to be * delivered again. */ handleEvent(pattern: string, packet: ReadPacket, context: KafkaContext): Promise<any>; protected initializeSerializer(options: KafkaOptions['options']): void; protected initializeDeserializer(options: KafkaOptions['options']): void; }