/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { Message, MessageCodec } from "#codec/MessageCodec.js"; import { Mark } from "#common/Mark.js"; import type { ExchangeLogContext, MessageExchange } from "#protocol/MessageExchange.js"; import type { Session } from "#session/Session.js"; import type { SessionParameters } from "#session/SessionParameters.js"; import { Bytes, Channel, ChannelType, Diagnostic, Duration, IpNetworkChannel, isIpNetworkChannel, isUdpNetworkChannel, Logger, MaybePromise, Observable, sameIpNetworkChannel, ServerAddress, ServerAddressIp, ServerAddressUdp, UdpNetworkChannel, } from "@matter/general"; import { MessageTooLargeError } from "./errors.js"; import { MRP } from "./MRP.js"; const logger = new Logger("MessageChannel"); export class MessageChannel implements Channel { #channel: Channel; #networkAddressChanged = Observable<[ServerAddressIp]>(); #isIpNetworkChannel = false; #channelAddressObserver?: (networkAddress: ServerAddressIp) => void; public closed = false; #onClose?: () => MaybePromise; // When the session is supporting MRP and the channel is not reliable, use MRP handling constructor( channel: Channel, readonly session: Session, onClose?: () => MaybePromise, ) { this.#channel = channel; if (isIpNetworkChannel(channel)) { this.#isIpNetworkChannel = true; this.#observeChannelAddress(channel); } this.#onClose = onClose; } set onClose(callback: () => MaybePromise) { this.#onClose = callback; } /** Is the underlying transport reliable? */ get isReliable() { return this.#channel.isReliable; } /** * Does the underlying transport support large messages? * This is only true for TCP channels currently. */ get supportsLargeMessages() { return this.#channel.supportsLargeMessages; } get type() { return this.#channel.type; } /** * Maximum size of an encoded Matter message sent on this channel. * * On TCP this is also capped at {@link Session.peerMaxTcpMessageSize}, because the peer closes the connection when * it receives a larger message. * * @see {@link MatterSpecification.v161.Core} § 4.15.2.3 */ get maxPayloadSize() { const channelMax = this.#channel.maxPayloadSize; if (this.type !== ChannelType.TCP) { return channelMax; } return Math.min(channelMax, this.session.peerMaxTcpMessageSize); } async send(message: Message, options?: MessageChannelSendOptions) { const { exchange, addressOverride } = options ?? {}; let { logContext } = options ?? {}; if (addressOverride && this.#isIpNetworkChannel) { logContext = { ...logContext, address: ServerAddress.urlFor(addressOverride), }; } logger.debug("Message", Mark.OUTBOUND, Message.diagnosticsOf(exchange ?? this.session, message, logContext)); const packet = this.session.encode(message); const bytes = MessageCodec.encodePacket(packet); if (bytes.byteLength > this.maxPayloadSize) { if (this.type === ChannelType.TCP) { // The peer closes the TCP connection on an oversized message, which would end every exchange on it throw new MessageTooLargeError( `Matter message to send to ${this.name} is ${bytes.byteLength} bytes long, which exceeds the TCP limit of ${this.maxPayloadSize}; split it by maxPayloadSize`, ); } logger.warn( `Matter message to send to ${this.name} is ${bytes.byteLength}bytes long, which is larger than the maximum allowed size of ${this.maxPayloadSize}. This only works if both nodes support it.`, ); } if (addressOverride && isUdpNetworkChannel(this.#channel)) { return await (this.#channel as UdpNetworkChannel).send(bytes, addressOverride); } return await this.#channel.send(bytes); } get name() { return Diagnostic.via(`${this.session.via}@${this.#channel.name}`); } get networkAddress(): ServerAddressIp | undefined { if (this.#isIpNetworkChannel) { return (this.#channel as IpNetworkChannel).networkAddress; } } set networkAddress(networkAddress: ServerAddressIp) { if (this.#isIpNetworkChannel) { (this.#channel as IpNetworkChannel).networkAddress = networkAddress; } } get networkAddressChanged() { return this.#networkAddressChanged; } /** The underlying transport channel, for identity comparison and type inspection. */ get transportChannel(): Channel { return this.#channel; } /** * Sync the addresses for IP network channels and replace channel if the IPs change * If the channel is on a non ip network then the call is basically ignored * We already use a new naming here which will be more used in future, so yes inconsistency in naming is ok for now * TODO refactor this out again and remove the address from the channel */ set socket(channel: Channel) { if ( this.closed || !this.#isIpNetworkChannel || !isIpNetworkChannel(channel) || channel.type !== "udp" || this.#channel.type !== "udp" ) { return; } const addressChanged = !sameIpNetworkChannel(channel, this.#channel as IpNetworkChannel); // Resubscribe address observer before replacing, so we detach from the old channel this.#observeChannelAddress(channel); // Always replace the underlying channel so references stay fresh, even when addresses match this.#channel = channel; if (addressChanged) { logger.debug(`Updated address of channel to`, this.name); this.#networkAddressChanged.emit(channel.networkAddress); } } #observeChannelAddress(newChannel: IpNetworkChannel) { // Detach from previous channel if (this.#channelAddressObserver && this.#isIpNetworkChannel) { (this.#channel as IpNetworkChannel).networkAddressChanged.off(this.#channelAddressObserver); } this.#channelAddressObserver = (networkAddress: ServerAddressIp) => { logger.debug(`Network address of channel changed to ${ServerAddress.urlFor(networkAddress)}`); this.#networkAddressChanged.emit(networkAddress); }; newChannel.networkAddressChanged.on(this.#channelAddressObserver); } async close() { const wasAlreadyClosed = this.closed; this.closed = true; this.#unobserveChannelAddress(); // TCP connections are 1:1 with sessions — lifecycle managed by ExchangeManager // (session eviction on disconnect, channel close on session close). UDP/BLE // channels are ephemeral per-session and closed directly here. if (this.#channel.type !== ChannelType.TCP) { await this.#channel.close(); } if (!wasAlreadyClosed) { await this.#onClose?.(); } } /** * Release the channel without closing the underlying transport channel, for use when the transport rather than the * session owns it. Closing a BLE channel disconnects the peripheral and closing a connected transport channel * drops messages of other sessions using it. */ async release() { const wasAlreadyClosed = this.closed; this.closed = true; this.#unobserveChannelAddress(); if (!wasAlreadyClosed) { await this.#onClose?.(); } } #unobserveChannelAddress() { if (this.#channelAddressObserver && this.#isIpNetworkChannel) { (this.#channel as IpNetworkChannel).networkAddressChanged.off(this.#channelAddressObserver); this.#channelAddressObserver = undefined; } } calculateMaximumPeerResponseTime( peerSessionParameters: SessionParameters, localSessionParameters: SessionParameters, expectedProcessingTime?: Duration, includeMaximumSendingTime?: boolean, localAdditionalDelay?: Duration, localFixedBackoff?: Duration, ): Duration { return MRP.maxPeerResponseTimeOf({ peerSessionParameters: includeMaximumSendingTime ? peerSessionParameters : undefined, localSessionParameters, channelType: this.#channel.type, isPeerActive: this.session.isPeerActive, usesMrp: this.session.usesMrp, expectedProcessingTime, localAdditionalDelay, localFixedBackoff, }); } /** * Calculates the backoff time for a resubmission based on the current retransmission count. * If no session parameters are provided, the parameters of the current session are used. * If session parameters are provided, the method can be used to calculate the maximum backoff time for the other * side of the exchange. * * When `calculateMaximum` is set to true, we calculate the maximum time without any randomness. * * @see {@link MatterSpecification.v161.Core}, section 4.12.2.1 */ getMrpResubmissionBackOffTime( retransmissionCount: number, sessionParameters?: SessionParameters, calculateMaximum = false, additionalDelay?: Duration, fixedBackoff?: Duration, ) { return MRP.retransmissionIntervalOf( { transmissionNumber: retransmissionCount, sessionParameters: sessionParameters ?? this.session.parameters, isPeerActive: this.session.isPeerActive, additionalDelay, fixedBackoff, }, calculateMaximum, ); } } export interface MessageChannelSendOptions { /** The exchange initiating the send, used for diagnostics. */ exchange?: MessageExchange; /** Additional context for logging. */ logContext?: ExchangeLogContext; /** Override the destination address for this send without changing the channel's default address. */ addressOverride?: ServerAddressUdp; }