import { Observable, ObservedValueOf, ReplaySubject, Subscription } from 'rxjs';
import { BaseRpcContext } from '../ctx-host/base-rpc.context.js';
import { Transport } from '../enums/index.js';
import { ConsumerDeserializer } from '../interfaces/deserializer.interface.js';
import { ClientOptions, MessageHandler, MicroserviceOptions, MsPattern, ReadPacket, WritePacket } from '../interfaces/index.js';
import { ConsumerSerializer } from '../interfaces/serializer.interface.js';
import { ITransportServer, type LoggerService } from '@nestjs/common';
/**
 * @publicApi
 */
export declare abstract class Server<EventsMap extends Record<string, Function> = Record<string, Function>, Status extends string = string> implements ITransportServer {
    /**
     * Unique transport identifier.
     */
    transportId?: Transport | symbol;
    protected readonly messageHandlers: Map<string, MessageHandler<any, any, any>>;
    protected readonly logger: LoggerService;
    /**
     * Event handlers that have replied to a request, so that the deprecation
     * is logged once per pattern.
     */
    private readonly eventHandlersThatReplied;
    /**
     * Whether this transport hands an event handler failure to its client
     * library, which then reports it. The base `handleEvent` connects the
     * stream without subscribing, so nothing observes the failure and Nest logs
     * it instead. `ServerKafka` awaits the stream and sets this to `true`.
     */
    readonly propagatesEventHandlerErrors: boolean;
    protected serializer: ConsumerSerializer;
    protected deserializer: ConsumerDeserializer;
    protected onProcessingStartHook: (transportId: Transport | symbol, context: BaseRpcContext, done: () => Promise<any>) => void;
    protected onProcessingEndHook: (transportId: Transport | symbol, context: BaseRpcContext) => void;
    protected _status$: ReplaySubject<Status>;
    /**
     * Requests and events being handled. A request stays counted until its last
     * reply has been published.
     */
    private handlersInFlight;
    private readonly handlersInFlightListeners;
    /**
     * Returns an observable that emits status changes.
     */
    get status(): Observable<Status>;
    /**
     * Registers an event listener for the given event.
     * @param event Event name
     * @param callback Callback to be executed when the event is emitted
     */
    abstract on<EventKey extends keyof EventsMap = keyof EventsMap, EventCallback extends EventsMap[EventKey] = EventsMap[EventKey]>(event: EventKey, callback: EventCallback): any;
    /**
     * Returns an instance of the underlying server/broker instance,
     * or a group of servers if there are more than one.
     */
    abstract unwrap<T>(): T;
    /**
     * Method called when server is being initialized.
     * @param callback Function to be called upon initialization
     */
    abstract listen(callback: (...optionalParams: unknown[]) => any): any;
    /**
     * Method called when server is being terminated.
     */
    abstract close(): any;
    /**
     * Sets the transport identifier.
     * @param transportId Unique transport identifier.
     */
    setTransportId(transportId: Transport | symbol): void;
    /**
     * Sets a hook that will be called when processing starts.
     */
    setOnProcessingStartHook(hook: (transportId: Transport | symbol, context: unknown, done: () => Promise<any>) => void): void;
    /**
     * Sets a hook that will be called when processing ends.
     */
    setOnProcessingEndHook(hook: (transportId: Transport | symbol, context: unknown) => void): void;
    addHandler(pattern: any, callback: MessageHandler, isEventHandler?: boolean, extras?: Record<string, any>): void;
    getHandlers(): Map<string, MessageHandler>;
    getHandlerByPattern(pattern: string): MessageHandler | null;
    send(stream$: Observable<any>, respond: (data: WritePacket) => Promise<unknown> | void): Subscription;
    /**
     * @param handler - the handler of `pattern`, if it was looked up already
     */
    handleEvent(pattern: string, packet: ReadPacket, context: BaseRpcContext, handler?: MessageHandler | null): Promise<any>;
    /**
     * Handles a request-response message. `produce` returns the response
     * stream, whose values are replied through `respond`, and the processing
     * end hook runs once that stream settles (or once `produce` rejects).
     */
    protected handleRequest(context: BaseRpcContext, produce: () => Promise<Observable<any>>, respond: (data: WritePacket) => Promise<unknown> | void): void;
    /**
     * Whether a request is answered with an error when `produce` rejects with
     * `err`, rather than only passing the rejection on to the transport.
     */
    protected shouldAnswerRejectedRequest(err: unknown): boolean;
    /**
     * Logs a deprecation warning the first time an event handler is about to
     * reply to a request (a packet with an id, sent with `ClientProxy#send`).
     * Event handlers still reply to requests, except on Kafka, but will not in
     * the next major version.
     */
    protected warnIfEventHandlerReplies(handler: MessageHandler, pattern: string): void;
    /**
     * Runs `fn` between the processing start and end hooks.
     *
     * `fn` receives a runner that closes the span exactly once and attaches it
     * to the teardown of whatever stream it produces. If `fn` rejects before
     * that teardown can run, the span is closed here and the rejection travels
     * on to the transport's client library.
     *
     * `endHookContext` is for transports that report a different context to
     * the end hook than to the start hook (gRPC passes the request).
     */
    protected runWithProcessingHooks(context: BaseRpcContext, fn: (runEndHook: () => void) => Promise<void>, endHookContext?: BaseRpcContext): void;
    /**
     * Resolves once no request or event is being handled, or after
     * `gracePeriod` milliseconds, whichever comes first. The period is 10
     * seconds unless a number is given.
     *
     * A transport calls it from `close()`, after it has stopped receiving
     * messages and before it closes its connection, so that the handlers in
     * flight can finish and publish their replies. A handler whose stream never
     * completes stays in flight, so the wait then lasts the whole period.
     *
     * A message counts from the moment its handling starts, once it has been
     * deserialized. With an asynchronous deserializer, a message received right
     * before `close()` may not be counted yet, so its handler can still run
     * after the connection has been closed.
     */
    protected waitForHandlersInFlight(gracePeriod?: number): Promise<void>;
    /**
     * Reads `gracePeriod` the same way for every transport: a value that is not
     * a number (NaN, "10s") gets the default period rather than none, a string
     * such as "5000" (e.g. from an environment variable) is a number, and a
     * longer one than a timer supports (e.g. Infinity, to wait until the
     * handlers are done) is capped.
     */
    protected normalizeGracePeriod(gracePeriod: unknown): number;
    /**
     * Counts a handler as in flight until the returned function is called.
     * Calling it again does nothing.
     */
    private trackHandlerInFlight;
    /**
     * Returns a function that runs the processing end hook exactly once.
     *
     * An event handler can fail either by rejecting or by returning a stream
     * that errors, and `ServerKafka#handleEvent` awaits that stream, so both the
     * `finalize` teardown and the `catch` block can be reached for a single
     * event. The hook closes a span, so it must not run twice.
     */
    protected createProcessingEndHookRunner(context: BaseRpcContext): () => void;
    transformToObservable<T>(resultOrDeferred: Observable<T> | Promise<T>): Observable<T>;
    transformToObservable<T>(resultOrDeferred: T): never extends Observable<ObservedValueOf<T>> ? Observable<T> : Observable<ObservedValueOf<T>>;
    getOptionsProp<Options extends MicroserviceOptions['options'], Attribute extends keyof Options>(obj: Options, prop: Attribute): Options[Attribute];
    getOptionsProp<Options extends MicroserviceOptions['options'], Attribute extends keyof Options, DefaultValue extends Options[Attribute] = Options[Attribute]>(obj: Options, prop: Attribute, defaultValue: DefaultValue): Required<Options>[Attribute];
    protected handleError(error: string): void;
    protected loadPackage<T = any>(name: string, ctx: string, loader?: () => T): T | Promise<T>;
    protected loadPackageSynchronously<T = any>(name: string, ctx: string, loader?: () => T): T;
    protected initializeSerializer(options: ClientOptions['options']): void;
    protected initializeDeserializer(options: ClientOptions['options']): void;
    /**
     * Transforms the server Pattern to valid type and returns a route for him.
     *
     * @param  {string} pattern - server pattern
     * @returns string
     */
    protected getRouteFromPattern(pattern: string): string;
    protected normalizePattern(pattern: MsPattern): string;
    /**
     * Returns the string representation of an incoming message pattern.
     *
     * Patterns are client-controlled: serializing a deeply nested one makes
     * `JSON.stringify` throw a `RangeError`, which must not escape the message
     * handler (as an unhandled promise rejection that terminates the process).
     *
     * A pattern that exceeds the limits of a route is not serialized at all:
     * its handler would be looked up by parsing the text again, at several
     * times its size in memory, only for its route to say which limit it
     * exceeds. That route is returned instead.
     *
     * @param  {unknown} pattern - client pattern
     * @returns string
     */
    protected getPatternAsString(pattern: unknown): string;
    /**
     * Throws unless the id of an incoming request is a number or a short string.
     *
     * Ids are client-controlled and every reply to the request carries a copy,
     * so a long string or a nested value would be copied and serialized once
     * per reply, which a handler that streams its response multiplies.
     *
     * @param  {unknown} id - request id
     */
    protected assertValidPacketId(id: unknown): void;
}
