@bymax-one/nest-realtime 1.2.18 → 1.2.20

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.
@@ -912,6 +912,45 @@ interface ITransport {
912
912
  onApplicationShutdown?(): Promise<void>;
913
913
  }
914
914
 
915
+ /** Why a handshake was refused. */
916
+ declare const REFUSAL_REASONS: readonly ["limit", "unauthorized", "unavailable", "error"];
917
+ /** Why a connection was closed by the library or by a revocation. */
918
+ declare const EVICTION_REASONS: readonly ["per_user_cap", "slow_consumer", "revoked"];
919
+ /** The transports a count is kept for. */
920
+ declare const TALLY_TRANSPORTS: readonly ["sse", "websocket"];
921
+ /** A reason a handshake is refused, one of `REFUSAL_REASONS`. */
922
+ type RefusalReason = (typeof REFUSAL_REASONS)[number];
923
+ /** A reason a connection is closed, one of `EVICTION_REASONS`. */
924
+ type EvictionReason = (typeof EVICTION_REASONS)[number];
925
+ /** A transport a count is kept for, one of `TALLY_TRANSPORTS`. */
926
+ type TallyTransport = (typeof TALLY_TRANSPORTS)[number];
927
+ /**
928
+ * Counts what the transports do, in plain numbers.
929
+ *
930
+ * It exists so that the code that does the work never imports a metrics library: an application that
931
+ * publishes nothing pays for a few integer increments, and the optional `observability` subpath reads
932
+ * these numbers when it is scraped. Each count is keyed by a closed set, so no label can grow with the
933
+ * traffic, and nothing a client or a host supplied is ever a key.
934
+ */
935
+ declare class RealtimeMetricsTally {
936
+ #private;
937
+ /** A handshake was refused for `reason`. */
938
+ refused(reason: RefusalReason): void;
939
+ /** A connection was closed for `reason`. */
940
+ evicted(reason: EvictionReason): void;
941
+ /** An event was delivered through `transport` on this instance. */
942
+ emitted(transport: TallyTransport): void;
943
+ /** A connection was cut for not reading what it was sent. */
944
+ slowConsumerDropped(): void;
945
+ /** The counts so far, as copies. */
946
+ snapshot(): {
947
+ readonly refused: Readonly<Record<RefusalReason, number>>;
948
+ readonly evicted: Readonly<Record<EvictionReason, number>>;
949
+ readonly emitted: Readonly<Record<TallyTransport, number>>;
950
+ readonly slowConsumerDrops: number;
951
+ };
952
+ }
953
+
915
954
  /**
916
955
  * Transport-agnostic realtime API.
917
956
  *
@@ -922,7 +961,8 @@ interface ITransport {
922
961
  declare class RealtimeService {
923
962
  private readonly transport;
924
963
  private readonly pubsub?;
925
- constructor(transport: ITransport, pubsub?: IRealtimePubSub | undefined);
964
+ private readonly tally?;
965
+ constructor(transport: ITransport, pubsub?: IRealtimePubSub | undefined, tally?: RealtimeMetricsTally | undefined);
926
966
  /**
927
967
  * Whether this instance hears the events and revocations other instances publish. False while
928
968
  * the bus is unreachable or its subscriber connection is down, so a readiness probe can take a
@@ -991,6 +1031,38 @@ declare class RealtimeService {
991
1031
  disconnect(connectionId: string, reason?: string): Promise<void>;
992
1032
  }
993
1033
 
1034
+ /** The span names the library starts. */
1035
+ type RealtimeSpanName = 'realtime.handshake' | 'realtime.reauthenticate';
1036
+ /** Attributes are closed: a transport name or an outcome, never an id, a tenant or a payload. */
1037
+ type RealtimeSpanAttributes = Readonly<Record<string, string>>;
1038
+ /**
1039
+ * Starts a span around an operation when `@opentelemetry/api` is installed, and runs it bare otherwise.
1040
+ *
1041
+ * The peer is optional, so it is loaded with a dynamic `import()` that a missing package turns into a no-op:
1042
+ * the root bundle never names it statically, and an application that does not trace installs nothing. With
1043
+ * the API present and no SDK registered the API itself is a no-op. A span carries a closed set of attributes
1044
+ * and, on failure, the library error code and nothing of the message.
1045
+ */
1046
+ declare class RealtimeTracing implements OnModuleInit {
1047
+ #private;
1048
+ /** Load the API once, at start-up; a package that is not there leaves the seam inert. */
1049
+ onModuleInit(): Promise<void>;
1050
+ /** Run the operation and report it on the span, where nothing the span does can change what comes back. */
1051
+ private traced;
1052
+ /**
1053
+ * Run `run` inside a span named `name`.
1054
+ *
1055
+ * The tracer belongs to the host's SDK, so it is never trusted with the operation: whatever it returns or
1056
+ * throws is ignored, the operation runs exactly once, through the span when the tracer started it and bare
1057
+ * otherwise, and its own result or error is what comes back.
1058
+ *
1059
+ * @param name - One of the library's span names.
1060
+ * @param attributes - Closed-set attributes of the span.
1061
+ * @param run - The operation; its result or its error passes through unchanged.
1062
+ */
1063
+ span<T>(name: RealtimeSpanName, attributes: RealtimeSpanAttributes, run: () => Promise<T>): Promise<T>;
1064
+ }
1065
+
994
1066
  /**
995
1067
  * @fileoverview Periodic re-authentication service with positive-result cache.
996
1068
  * @layer application
@@ -1013,14 +1085,19 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
1013
1085
  private readonly realtime;
1014
1086
  private readonly auth;
1015
1087
  private readonly hooks?;
1088
+ private readonly tracing?;
1016
1089
  private readonly logger;
1017
1090
  private timer;
1018
1091
  private readonly policy;
1092
+ /** The policy as the host wrote it: the cache check compares the two figures only when both were set. */
1093
+ private readonly declared;
1019
1094
  /** Connections with a revalidation queued or running: one call at a time for each. */
1020
1095
  private readonly inFlight;
1021
1096
  /** The cap on revalidations in flight, shared by every cycle. */
1022
1097
  private readonly slots;
1023
- constructor(connections: ConnectionRegistry, realtime: RealtimeService, auth: IConnectionAuthenticator, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined);
1098
+ constructor(connections: ConnectionRegistry, realtime: RealtimeService, auth: IConnectionAuthenticator, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, tracing?: RealtimeTracing | undefined);
1099
+ /** Warn once, through the application's logger, when the positive cache outlives the interval. */
1100
+ private warnIfCacheOutlivesInterval;
1024
1101
  /**
1025
1102
  * Schedule the periodic revalidation cycle.
1026
1103
  *
@@ -1082,6 +1159,8 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
1082
1159
  */
1083
1160
  declare class AuthenticationUnavailableError extends Error {
1084
1161
  readonly reason: 'saturated' | 'timeout';
1162
+ /** The code the refusal travels under, so a span or a log names it without reading the message. */
1163
+ readonly code: "REALTIME_TRANSPORT_UNAVAILABLE";
1085
1164
  constructor(reason: 'saturated' | 'timeout');
1086
1165
  }
1087
1166
  /**
@@ -1116,6 +1195,8 @@ declare class AuthenticationGate {
1116
1195
  /** A handshake was refused because the instance already holds `maxConnections` connections. */
1117
1196
  declare class ConnectionLimitError extends Error {
1118
1197
  readonly limit: number;
1198
+ /** The code the refusal travels under, so a span or a log names it without reading the message. */
1199
+ readonly code: "REALTIME_TRANSPORT_UNAVAILABLE";
1119
1200
  constructor(limit: number);
1120
1201
  }
1121
1202
  /** A place held for a connection that has been admitted and is not registered yet. */
@@ -1522,10 +1603,11 @@ declare class SseTransport implements ITransport {
1522
1603
  private readonly instanceId;
1523
1604
  private readonly offlineQueue?;
1524
1605
  private readonly admission?;
1606
+ private readonly tally?;
1525
1607
  readonly kind: "sse";
1526
1608
  private readonly logger;
1527
1609
  private readonly outbound;
1528
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, gate: AuthenticationGate, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined, admission?: ConnectionAdmission | undefined);
1610
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, gate: AuthenticationGate, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined, admission?: ConnectionAdmission | undefined, tally?: RealtimeMetricsTally | undefined);
1529
1611
  /**
1530
1612
  * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
1531
1613
  * nearer the root than the realtime module still runs first, and until it returns a stream is
@@ -1697,9 +1779,11 @@ declare class SseSubscriptionHandler {
1697
1779
  private readonly options;
1698
1780
  private readonly hooks?;
1699
1781
  private readonly offlineDelivery?;
1782
+ private readonly tally?;
1783
+ private readonly tracing?;
1700
1784
  private readonly logger;
1701
1785
  private readonly authenticated;
1702
- constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
1786
+ constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined, tally?: RealtimeMetricsTally | undefined, tracing?: RealtimeTracing | undefined);
1703
1787
  /**
1704
1788
  * Resolve the tenant this connection routes on, and refuse a blank identity.
1705
1789
  *
@@ -1756,7 +1840,9 @@ declare class SseSubscriptionHandler {
1756
1840
  authenticateBeforeCommit(req: SseRequest, res?: SseResponse): Promise<void>;
1757
1841
  private toClientError;
1758
1842
  private serverError;
1843
+ /** Admit and authenticate a handshake, inside the `realtime.handshake` span when tracing is wired. */
1759
1844
  private authenticateRequest;
1845
+ private admitAndAuthenticate;
1760
1846
  /**
1761
1847
  * Read the offline queue's gap for a reconnect, WITHOUT acknowledging (acknowledgment is deferred
1762
1848
  * until the events have been emitted to an open subscriber, so delivery is at-least-once).
@@ -1896,6 +1982,8 @@ declare class RealtimePubSubSubscriber implements OnModuleInit, OnApplicationShu
1896
1982
  */
1897
1983
  private readonly dropped;
1898
1984
  private handle;
1985
+ /** Close a connection another instance asked this one to close; the handler is synchronous, so a rejection is handled here. */
1986
+ private closeLocal;
1899
1987
  private drop;
1900
1988
  }
1901
1989
 
@@ -2002,6 +2090,7 @@ declare class RedisRealtimePubSub implements IRealtimePubSub {
2002
2090
  /** A server that was reached and refused the SUBSCRIBE after boot: it stays unsubscribed. */
2003
2091
  private refused;
2004
2092
  private markUp;
2093
+ /** The bus is not subscribed: `wording` is the library's own text, `error` what the connection raised. */
2005
2094
  private markDown;
2006
2095
  /**
2007
2096
  * Count a payload dropped as unparsable and report the count at most once per minute, so a
@@ -2191,6 +2280,38 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
2191
2280
  /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
2192
2281
  declare function describeError(reason: unknown): string;
2193
2282
 
2283
+ /**
2284
+ * @fileoverview The one way the library writes an operational log line: an object with a stable event code.
2285
+ * @layer utils
2286
+ */
2287
+
2288
+ /**
2289
+ * The event codes the library logs at `warn` and `error`. Each is listed with its fields in the README
2290
+ * "Log events" table; a code is never reused for another condition, so a host can alert on one.
2291
+ */
2292
+ declare const REALTIME_LOG_EVENTS: readonly ["REALTIME_REAUTH_CACHE_WEAKENS_POLICY", "REALTIME_HANDSHAKE_FAILED", "REALTIME_HOOK_FAILED", "REALTIME_DELIVERY_FAILED", "REALTIME_SLOW_CONSUMER", "REALTIME_DISCONNECT_FAILED", "REALTIME_RECONNECTS_GIVEN_UP", "REALTIME_OFFLINE_QUEUE_LIMIT", "REALTIME_OFFLINE_QUEUE_ACK_FAILED", "REALTIME_PUBSUB_NOT_PROVIDED", "REALTIME_PUBSUB_UNSUBSCRIBE_FAILED", "REALTIME_PUBSUB_DROPPED", "REALTIME_PUBSUB_UNAVAILABLE", "REALTIME_CONNECTIONS_REFUSED", "REALTIME_HANDSHAKES_REFUSED", "REALTIME_REAUTH_FAILED", "REALTIME_REVOCATION_FAILED", "REALTIME_ADAPTER_MISSING", "REALTIME_ADAPTER_COMMAND_FAILED", "REALTIME_COMPOSITE_PARTIAL_FAILURE", "REALTIME_SERVER_NOT_ATTACHED"];
2293
+ /** The code of one warn or error event the library writes, one of `REALTIME_LOG_EVENTS`. */
2294
+ type RealtimeLogEvent = (typeof REALTIME_LOG_EVENTS)[number];
2295
+ /** Fields are closed or numeric: a count, a size, a configured limit, a transport name or a library-made id. */
2296
+ type LogFields = Readonly<Record<string, string | number | boolean>>;
2297
+ /**
2298
+ * Write `message` as an operational event.
2299
+ *
2300
+ * The line is an object, so a structured logger writes `event`, `message` and each field as separate JSON
2301
+ * fields and Nest's default logger prints it readably. Nothing a host supplied (a user or tenant id, a room, an
2302
+ * endpoint) belongs in `message` or `fields`: the logger's own correlation context already carries identity.
2303
+ *
2304
+ * @param logger - The component's logger.
2305
+ * @param level - `warn` for what degrades service, `error` for what fails an operation.
2306
+ * @param event - The stable code of the condition.
2307
+ * @param message - Human text; the library's own wording, with no host-supplied value in it.
2308
+ * @param fields - Closed or numeric fields.
2309
+ * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2310
+ * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
2311
+ * carry a user or a tenant, and the library's own line must not.
2312
+ */
2313
+ declare function logEvent(logger: Pick<Logger, 'warn' | 'error'>, level: 'warn' | 'error', event: RealtimeLogEvent, message: string, fields?: LogFields, error?: unknown): void;
2314
+
2194
2315
  /**
2195
2316
  * @fileoverview Closing a Redis connection without waiting on a server that has stopped answering.
2196
2317
  * @layer infrastructure
@@ -2253,7 +2374,8 @@ type UnavailableError = ServiceUnavailableException & {
2253
2374
  /**
2254
2375
  * Builds the rejection for a call whose effect did not happen, such as a revocation that never
2255
2376
  * reached its connection. The stable code leads the message, as it does in the other errors this
2256
- * library raises, is also the `code` property, and the original failure travels as `cause`.
2377
+ * library raises, is also the `code` property, and the original failure travels as `cause` alone: its
2378
+ * text, which is a driver's or a host's, is not in the message.
2257
2379
  *
2258
2380
  * It is Nest's `ServiceUnavailableException`, so a consumer's controller that lets it escape
2259
2381
  * answers 503 with the generic body, and the library's own text never reaches a client: the
@@ -2451,5 +2573,5 @@ declare const RESERVED_EVENT_NAMES: {
2451
2573
  /** Union of reserved event name values. */
2452
2574
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2453
2575
 
2454
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
2455
- export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
2576
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EVICTION_REASONS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_LOG_EVENTS, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, REFUSAL_REASONS, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeMetricsTally, RealtimePubSubSubscriber, RealtimeService, RealtimeTracing, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, TALLY_TRANSPORTS, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, logEvent, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
2577
+ export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, EvictionReason, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, LogFields, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimeLogEvent, RealtimePubSubMessage, RealtimeSpanAttributes, RealtimeSpanName, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, RefusalReason, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TallyTransport, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
@@ -912,6 +912,45 @@ interface ITransport {
912
912
  onApplicationShutdown?(): Promise<void>;
913
913
  }
914
914
 
915
+ /** Why a handshake was refused. */
916
+ declare const REFUSAL_REASONS: readonly ["limit", "unauthorized", "unavailable", "error"];
917
+ /** Why a connection was closed by the library or by a revocation. */
918
+ declare const EVICTION_REASONS: readonly ["per_user_cap", "slow_consumer", "revoked"];
919
+ /** The transports a count is kept for. */
920
+ declare const TALLY_TRANSPORTS: readonly ["sse", "websocket"];
921
+ /** A reason a handshake is refused, one of `REFUSAL_REASONS`. */
922
+ type RefusalReason = (typeof REFUSAL_REASONS)[number];
923
+ /** A reason a connection is closed, one of `EVICTION_REASONS`. */
924
+ type EvictionReason = (typeof EVICTION_REASONS)[number];
925
+ /** A transport a count is kept for, one of `TALLY_TRANSPORTS`. */
926
+ type TallyTransport = (typeof TALLY_TRANSPORTS)[number];
927
+ /**
928
+ * Counts what the transports do, in plain numbers.
929
+ *
930
+ * It exists so that the code that does the work never imports a metrics library: an application that
931
+ * publishes nothing pays for a few integer increments, and the optional `observability` subpath reads
932
+ * these numbers when it is scraped. Each count is keyed by a closed set, so no label can grow with the
933
+ * traffic, and nothing a client or a host supplied is ever a key.
934
+ */
935
+ declare class RealtimeMetricsTally {
936
+ #private;
937
+ /** A handshake was refused for `reason`. */
938
+ refused(reason: RefusalReason): void;
939
+ /** A connection was closed for `reason`. */
940
+ evicted(reason: EvictionReason): void;
941
+ /** An event was delivered through `transport` on this instance. */
942
+ emitted(transport: TallyTransport): void;
943
+ /** A connection was cut for not reading what it was sent. */
944
+ slowConsumerDropped(): void;
945
+ /** The counts so far, as copies. */
946
+ snapshot(): {
947
+ readonly refused: Readonly<Record<RefusalReason, number>>;
948
+ readonly evicted: Readonly<Record<EvictionReason, number>>;
949
+ readonly emitted: Readonly<Record<TallyTransport, number>>;
950
+ readonly slowConsumerDrops: number;
951
+ };
952
+ }
953
+
915
954
  /**
916
955
  * Transport-agnostic realtime API.
917
956
  *
@@ -922,7 +961,8 @@ interface ITransport {
922
961
  declare class RealtimeService {
923
962
  private readonly transport;
924
963
  private readonly pubsub?;
925
- constructor(transport: ITransport, pubsub?: IRealtimePubSub | undefined);
964
+ private readonly tally?;
965
+ constructor(transport: ITransport, pubsub?: IRealtimePubSub | undefined, tally?: RealtimeMetricsTally | undefined);
926
966
  /**
927
967
  * Whether this instance hears the events and revocations other instances publish. False while
928
968
  * the bus is unreachable or its subscriber connection is down, so a readiness probe can take a
@@ -991,6 +1031,38 @@ declare class RealtimeService {
991
1031
  disconnect(connectionId: string, reason?: string): Promise<void>;
992
1032
  }
993
1033
 
1034
+ /** The span names the library starts. */
1035
+ type RealtimeSpanName = 'realtime.handshake' | 'realtime.reauthenticate';
1036
+ /** Attributes are closed: a transport name or an outcome, never an id, a tenant or a payload. */
1037
+ type RealtimeSpanAttributes = Readonly<Record<string, string>>;
1038
+ /**
1039
+ * Starts a span around an operation when `@opentelemetry/api` is installed, and runs it bare otherwise.
1040
+ *
1041
+ * The peer is optional, so it is loaded with a dynamic `import()` that a missing package turns into a no-op:
1042
+ * the root bundle never names it statically, and an application that does not trace installs nothing. With
1043
+ * the API present and no SDK registered the API itself is a no-op. A span carries a closed set of attributes
1044
+ * and, on failure, the library error code and nothing of the message.
1045
+ */
1046
+ declare class RealtimeTracing implements OnModuleInit {
1047
+ #private;
1048
+ /** Load the API once, at start-up; a package that is not there leaves the seam inert. */
1049
+ onModuleInit(): Promise<void>;
1050
+ /** Run the operation and report it on the span, where nothing the span does can change what comes back. */
1051
+ private traced;
1052
+ /**
1053
+ * Run `run` inside a span named `name`.
1054
+ *
1055
+ * The tracer belongs to the host's SDK, so it is never trusted with the operation: whatever it returns or
1056
+ * throws is ignored, the operation runs exactly once, through the span when the tracer started it and bare
1057
+ * otherwise, and its own result or error is what comes back.
1058
+ *
1059
+ * @param name - One of the library's span names.
1060
+ * @param attributes - Closed-set attributes of the span.
1061
+ * @param run - The operation; its result or its error passes through unchanged.
1062
+ */
1063
+ span<T>(name: RealtimeSpanName, attributes: RealtimeSpanAttributes, run: () => Promise<T>): Promise<T>;
1064
+ }
1065
+
994
1066
  /**
995
1067
  * @fileoverview Periodic re-authentication service with positive-result cache.
996
1068
  * @layer application
@@ -1013,14 +1085,19 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
1013
1085
  private readonly realtime;
1014
1086
  private readonly auth;
1015
1087
  private readonly hooks?;
1088
+ private readonly tracing?;
1016
1089
  private readonly logger;
1017
1090
  private timer;
1018
1091
  private readonly policy;
1092
+ /** The policy as the host wrote it: the cache check compares the two figures only when both were set. */
1093
+ private readonly declared;
1019
1094
  /** Connections with a revalidation queued or running: one call at a time for each. */
1020
1095
  private readonly inFlight;
1021
1096
  /** The cap on revalidations in flight, shared by every cycle. */
1022
1097
  private readonly slots;
1023
- constructor(connections: ConnectionRegistry, realtime: RealtimeService, auth: IConnectionAuthenticator, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined);
1098
+ constructor(connections: ConnectionRegistry, realtime: RealtimeService, auth: IConnectionAuthenticator, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, tracing?: RealtimeTracing | undefined);
1099
+ /** Warn once, through the application's logger, when the positive cache outlives the interval. */
1100
+ private warnIfCacheOutlivesInterval;
1024
1101
  /**
1025
1102
  * Schedule the periodic revalidation cycle.
1026
1103
  *
@@ -1082,6 +1159,8 @@ declare class ReauthenticationService implements OnModuleInit, OnApplicationShut
1082
1159
  */
1083
1160
  declare class AuthenticationUnavailableError extends Error {
1084
1161
  readonly reason: 'saturated' | 'timeout';
1162
+ /** The code the refusal travels under, so a span or a log names it without reading the message. */
1163
+ readonly code: "REALTIME_TRANSPORT_UNAVAILABLE";
1085
1164
  constructor(reason: 'saturated' | 'timeout');
1086
1165
  }
1087
1166
  /**
@@ -1116,6 +1195,8 @@ declare class AuthenticationGate {
1116
1195
  /** A handshake was refused because the instance already holds `maxConnections` connections. */
1117
1196
  declare class ConnectionLimitError extends Error {
1118
1197
  readonly limit: number;
1198
+ /** The code the refusal travels under, so a span or a log names it without reading the message. */
1199
+ readonly code: "REALTIME_TRANSPORT_UNAVAILABLE";
1119
1200
  constructor(limit: number);
1120
1201
  }
1121
1202
  /** A place held for a connection that has been admitted and is not registered yet. */
@@ -1522,10 +1603,11 @@ declare class SseTransport implements ITransport {
1522
1603
  private readonly instanceId;
1523
1604
  private readonly offlineQueue?;
1524
1605
  private readonly admission?;
1606
+ private readonly tally?;
1525
1607
  readonly kind: "sse";
1526
1608
  private readonly logger;
1527
1609
  private readonly outbound;
1528
- constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, gate: AuthenticationGate, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined, admission?: ConnectionAdmission | undefined);
1610
+ constructor(connections: ConnectionRegistry, rooms: RoomRegistry, replayBuffer: EventReplayBuffer, idGen: EventIdGenerator, heartbeat: HeartbeatService, gate: AuthenticationGate, pubsub: IRealtimePubSub, hooks: IConnectionLifecycleHooks, options: BymaxRealtimeModuleOptions, instanceId: string, offlineQueue?: IOfflineQueueStorage | undefined, admission?: ConnectionAdmission | undefined, tally?: RealtimeMetricsTally | undefined);
1529
1611
  /**
1530
1612
  * Mark shutdown as begun at the first hook Nest runs on close. A slow `onModuleDestroy` in a module
1531
1613
  * nearer the root than the realtime module still runs first, and until it returns a stream is
@@ -1697,9 +1779,11 @@ declare class SseSubscriptionHandler {
1697
1779
  private readonly options;
1698
1780
  private readonly hooks?;
1699
1781
  private readonly offlineDelivery?;
1782
+ private readonly tally?;
1783
+ private readonly tracing?;
1700
1784
  private readonly logger;
1701
1785
  private readonly authenticated;
1702
- constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined);
1786
+ constructor(transport: SseTransport, heartbeat: HeartbeatService, options: BymaxRealtimeModuleOptions, hooks?: IConnectionLifecycleHooks | undefined, offlineDelivery?: OfflineQueueDeliveryService | undefined, tally?: RealtimeMetricsTally | undefined, tracing?: RealtimeTracing | undefined);
1703
1787
  /**
1704
1788
  * Resolve the tenant this connection routes on, and refuse a blank identity.
1705
1789
  *
@@ -1756,7 +1840,9 @@ declare class SseSubscriptionHandler {
1756
1840
  authenticateBeforeCommit(req: SseRequest, res?: SseResponse): Promise<void>;
1757
1841
  private toClientError;
1758
1842
  private serverError;
1843
+ /** Admit and authenticate a handshake, inside the `realtime.handshake` span when tracing is wired. */
1759
1844
  private authenticateRequest;
1845
+ private admitAndAuthenticate;
1760
1846
  /**
1761
1847
  * Read the offline queue's gap for a reconnect, WITHOUT acknowledging (acknowledgment is deferred
1762
1848
  * until the events have been emitted to an open subscriber, so delivery is at-least-once).
@@ -1896,6 +1982,8 @@ declare class RealtimePubSubSubscriber implements OnModuleInit, OnApplicationShu
1896
1982
  */
1897
1983
  private readonly dropped;
1898
1984
  private handle;
1985
+ /** Close a connection another instance asked this one to close; the handler is synchronous, so a rejection is handled here. */
1986
+ private closeLocal;
1899
1987
  private drop;
1900
1988
  }
1901
1989
 
@@ -2002,6 +2090,7 @@ declare class RedisRealtimePubSub implements IRealtimePubSub {
2002
2090
  /** A server that was reached and refused the SUBSCRIBE after boot: it stays unsubscribed. */
2003
2091
  private refused;
2004
2092
  private markUp;
2093
+ /** The bus is not subscribed: `wording` is the library's own text, `error` what the connection raised. */
2005
2094
  private markDown;
2006
2095
  /**
2007
2096
  * Count a payload dropped as unparsable and report the count at most once per minute, so a
@@ -2191,6 +2280,38 @@ declare function composeRoomId(prefix: keyof typeof ROOM_PREFIXES, ...parts: str
2191
2280
  /** Describe a thrown or rejected value without throwing: `.message` on `null`, or `String()` on a prototype-less object, would. */
2192
2281
  declare function describeError(reason: unknown): string;
2193
2282
 
2283
+ /**
2284
+ * @fileoverview The one way the library writes an operational log line: an object with a stable event code.
2285
+ * @layer utils
2286
+ */
2287
+
2288
+ /**
2289
+ * The event codes the library logs at `warn` and `error`. Each is listed with its fields in the README
2290
+ * "Log events" table; a code is never reused for another condition, so a host can alert on one.
2291
+ */
2292
+ declare const REALTIME_LOG_EVENTS: readonly ["REALTIME_REAUTH_CACHE_WEAKENS_POLICY", "REALTIME_HANDSHAKE_FAILED", "REALTIME_HOOK_FAILED", "REALTIME_DELIVERY_FAILED", "REALTIME_SLOW_CONSUMER", "REALTIME_DISCONNECT_FAILED", "REALTIME_RECONNECTS_GIVEN_UP", "REALTIME_OFFLINE_QUEUE_LIMIT", "REALTIME_OFFLINE_QUEUE_ACK_FAILED", "REALTIME_PUBSUB_NOT_PROVIDED", "REALTIME_PUBSUB_UNSUBSCRIBE_FAILED", "REALTIME_PUBSUB_DROPPED", "REALTIME_PUBSUB_UNAVAILABLE", "REALTIME_CONNECTIONS_REFUSED", "REALTIME_HANDSHAKES_REFUSED", "REALTIME_REAUTH_FAILED", "REALTIME_REVOCATION_FAILED", "REALTIME_ADAPTER_MISSING", "REALTIME_ADAPTER_COMMAND_FAILED", "REALTIME_COMPOSITE_PARTIAL_FAILURE", "REALTIME_SERVER_NOT_ATTACHED"];
2293
+ /** The code of one warn or error event the library writes, one of `REALTIME_LOG_EVENTS`. */
2294
+ type RealtimeLogEvent = (typeof REALTIME_LOG_EVENTS)[number];
2295
+ /** Fields are closed or numeric: a count, a size, a configured limit, a transport name or a library-made id. */
2296
+ type LogFields = Readonly<Record<string, string | number | boolean>>;
2297
+ /**
2298
+ * Write `message` as an operational event.
2299
+ *
2300
+ * The line is an object, so a structured logger writes `event`, `message` and each field as separate JSON
2301
+ * fields and Nest's default logger prints it readably. Nothing a host supplied (a user or tenant id, a room, an
2302
+ * endpoint) belongs in `message` or `fields`: the logger's own correlation context already carries identity.
2303
+ *
2304
+ * @param logger - The component's logger.
2305
+ * @param level - `warn` for what degrades service, `error` for what fails an operation.
2306
+ * @param event - The stable code of the condition.
2307
+ * @param message - Human text; the library's own wording, with no host-supplied value in it.
2308
+ * @param fields - Closed or numeric fields.
2309
+ * @param error - What was thrown, when the event reports a failure. It goes under `err` as the value itself, never
2310
+ * as text in `message`, so the logger's serializer and redaction apply to it: an error raised by host code can
2311
+ * carry a user or a tenant, and the library's own line must not.
2312
+ */
2313
+ declare function logEvent(logger: Pick<Logger, 'warn' | 'error'>, level: 'warn' | 'error', event: RealtimeLogEvent, message: string, fields?: LogFields, error?: unknown): void;
2314
+
2194
2315
  /**
2195
2316
  * @fileoverview Closing a Redis connection without waiting on a server that has stopped answering.
2196
2317
  * @layer infrastructure
@@ -2253,7 +2374,8 @@ type UnavailableError = ServiceUnavailableException & {
2253
2374
  /**
2254
2375
  * Builds the rejection for a call whose effect did not happen, such as a revocation that never
2255
2376
  * reached its connection. The stable code leads the message, as it does in the other errors this
2256
- * library raises, is also the `code` property, and the original failure travels as `cause`.
2377
+ * library raises, is also the `code` property, and the original failure travels as `cause` alone: its
2378
+ * text, which is a driver's or a host's, is not in the message.
2257
2379
  *
2258
2380
  * It is Nest's `ServiceUnavailableException`, so a consumer's controller that lets it escape
2259
2381
  * answers 503 with the generic body, and the library's own text never reaches a client: the
@@ -2451,5 +2573,5 @@ declare const RESERVED_EVENT_NAMES: {
2451
2573
  /** Union of reserved event name values. */
2452
2574
  type ReservedEventName = (typeof RESERVED_EVENT_NAMES)[keyof typeof RESERVED_EVENT_NAMES];
2453
2575
 
2454
- export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimePubSubSubscriber, RealtimeService, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
2455
- export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimePubSubMessage, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };
2576
+ export { ADMISSION_ROOM_LIMITS, AuthenticationGate, AuthenticationUnavailableError, BymaxRealtimeModule, ConnectionAdmission, ConnectionLimitError, ConnectionRegistry, DEFAULT_HOOK_TIMEOUT_MS, EVICTION_REASONS, EventIdGenerator, EventReplayBuffer, HeartbeatService, InMemoryPubSub, OfflineQueueDeliveryService, REALTIME_AUTHENTICATOR_TOKEN, REALTIME_ERROR_CODES, REALTIME_HOOKS_TOKEN, REALTIME_INSTANCE_ID_TOKEN, REALTIME_LOG_EVENTS, REALTIME_OFFLINE_QUEUE_TOKEN, REALTIME_OPTIONS_TOKEN, REALTIME_PRESENCE_TOKEN, REALTIME_PUBSUB_TOKEN, REALTIME_TRANSPORT_TOKEN, REFUSAL_REASONS, RESERVED_EVENT_NAMES, ROOM_PREFIXES, RealtimeMetricsTally, RealtimePubSubSubscriber, RealtimeService, RealtimeTracing, ReauthenticationService, RedisOfflineQueue, RedisRealtimePubSub, RoomRegistry, SseSubscriptionHandler, SseTransport, TALLY_TRANSPORTS, UNBOUNDED_TICKET, admitRooms, assertIdentityIsNotBlank, composeForRoot, composeForRootAsync, composeRoomId, createSseController, describeError, logEvent, parseCookieHeader, quitWithin, realtimeError, refuseReservedRoom, reportDeliveryFailure, requireRoomName, resolveAuthTenant, runHook, sseWiring, unavailableError };
2577
+ export type { AdmissionTicket, AuthenticationResult, AuthenticatorCallOptions, BymaxRealtimeModuleAsyncOptions, BymaxRealtimeModuleOptions, BymaxRealtimeModuleOptionsFactory, CodedError, ConnectionAuthContext, ConnectionEventMeta, CorsConfig, DeliveryFailure, EvictionReason, IConnectionAuthenticator, IConnectionLifecycleHooks, IOfflineQueueStorage, IPresenceStorage, IRealtimePubSub, ITransport, LogFields, OfflineQueuedEvent, PublicConnectionMeta, QuitableClient, RealtimeErrorCode, RealtimeEvent, RealtimeLogEvent, RealtimePubSubMessage, RealtimeSpanAttributes, RealtimeSpanName, ReauthenticationPolicy, RedisOfflineQueueOptions, RedisRealtimePubSubOptions, RefusalReason, ReservedEventName, RoomPrefix, SseOptions, SseRealtimeModuleAsyncOptions, SseRealtimeModuleOptions, TallyTransport, TransportMode, TransportRegistration, TransportWiring, WebSocketOptions, WebSocketRealtimeModuleAsyncOptions, WebSocketRealtimeModuleOptions };