/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { MdnsService } from "#mdns/MdnsService.js"; import { PeerAddress } from "#peer/PeerAddress.js"; import { ExchangeManager } from "#protocol/ExchangeManager.js"; import type { NodeSession } from "#session/NodeSession.js"; import { Session } from "#session/Session.js"; import { SessionManager } from "#session/SessionManager.js"; import { Abort, AsyncObservable, BasicSet, ChannelType, DeepPartial, DnssdNames, Environment, Environmental, ImmutableSet, ImplementationError, isIpNetworkChannel, isIPv6, Lifetime, MatterAggregateError, NetworkUnreachableError, ObservableSet, ObserverGroup, RetrySchedule, ServerAddressIp, } from "@matter/general"; import { NetworkProfiles } from "./NetworkProfile.js"; import { Peer } from "./Peer.js"; import { PeerConnection } from "./PeerConnection.js"; import { OperationalAddress, PeerDescriptor } from "./PeerDescriptor.js"; import { PeerTimingParameters } from "./PeerTimingParameters.js"; /** * Interfaces {@link PeerSet} with other components. */ export interface PeerSetContext { lifetime: Lifetime.Owner; sessions: SessionManager; names: DnssdNames; networks: NetworkProfiles; connectionRetries?: RetrySchedule; timing?: PeerTimingParameters; handleError?: PeerConnection.Context["handleError"]; } /** * Manages operational connections to peers on shared fabric. */ export class PeerSet implements ImmutableSet, ObservableSet { readonly #lifetime: Lifetime; readonly #sessions: SessionManager; readonly #peers = new BasicSet(); readonly #disconnected = AsyncObservable<[peer: Peer]>(); readonly #peerContext: Peer.Context; readonly #networks: NetworkProfiles; readonly #observers = new ObserverGroup(); #exchanges?: ExchangeManager; #transportPreference?: ChannelType.TCP; constructor(context: PeerSetContext) { const { lifetime, sessions, names, networks, timing, handleError } = context; this.#lifetime = lifetime.join("peers"); this.#sessions = sessions; this.#networks = networks; const self = this; this.#peerContext = { sessions, names, networks, timing: PeerTimingParameters(timing), handleError, get exchanges() { if (self.#exchanges === undefined) { throw new ImplementationError("Client networking is not initialized"); } return self.#exchanges; }, openSocket: (address, abort) => this.#openSocket(address, abort), closed: peer => this.#peers.delete(peer), join: name => this.#lifetime.join(name), }; this.#observers.on(this.#peers.added, peer => { // Scoped to the peer's own observable, so it needs no cleanup of ours peer.sessions.deleted.on(() => { if (!peer.sessions.size) { this.#disconnected.emit(peer); } }); }); this.#observers.on(this.#sessions.sessions.added, session => this.#adoptSession(session)); // Sessions may predate us: nothing guarantees we are instantiated before the node establishes its first // operational session for (const session of this.#sessions.sessions) { this.#adoptSession(session); } } /** * Associate an operational session with its peer, creating the peer if we do not know it yet. */ #adoptSession(session: NodeSession) { if (session.fabric === undefined || session.isClosed) { return; } this.addKnownPeer({ address: session.peerAddress, operationalAddress: operationalAddressOf(session), }).sessions.add(session); } set exchanges(exchanges: ExchangeManager | undefined) { this.#exchanges = exchanges; } get added() { return this.#peers.added; } get deleted() { return this.#peers.deleted; } get empty() { return this.#peers.empty; } get disconnected() { return this.#disconnected; } /** * Default outgoing transport preference applied to peers created by this set when they have * no per-peer override. Honored as a soft preference at connect time. */ get transportPreference() { return this.#transportPreference; } set transportPreference(pref: ChannelType.TCP | undefined) { this.#transportPreference = pref; } /** * Unconditional get. * * Creates the peer if not already present. */ for(address: PeerAddress) { let peer = this.get(address); if (peer) { return peer; } peer = new Peer({ address }, this.#peerContext); this.#applyDefaultPreference(peer); this.#peers.add(peer); return peer; } #applyDefaultPreference(peer: Peer) { if (peer.transportPreference === undefined && this.#transportPreference !== undefined) { peer.transportPreference = this.#transportPreference; } } has(item: PeerAddress | PeerDescriptor | Peer) { return !!this.get(item); } get size() { return this.#peers.size; } find(predicate: (item: Peer) => boolean | undefined) { return this.#peers.find(predicate); } filter(predicate: (item: Peer) => boolean | undefined) { return this.#peers.filter(predicate); } map(mapper: (item: Peer) => T) { return this.#peers.map(mapper); } [Symbol.iterator]() { return this.#peers[Symbol.iterator](); } static [Environmental.create](env: Environment) { const instance = new PeerSet({ lifetime: env, sessions: env.get(SessionManager), names: env.get(MdnsService).names, networks: env.get(NetworkProfiles), }); env.set(PeerSet, instance); return instance; } get peers() { return this.#peers; } get networks() { return this.#networks; } get timing() { return this.#peerContext.timing; } set timing(timing: DeepPartial) { this.#peerContext.timing = PeerTimingParameters(timing); } set handleError(handler: PeerConnection.Context["handleError"]) { this.#peerContext.handleError = handler; } /** * Retrieve a peer by address. */ get(peer: PeerAddress | PeerDescriptor) { if ("address" in peer) { return this.#peers.get("address", PeerAddress(peer.address)); } return this.#peers.get("address", PeerAddress(peer)); } /** * Terminate any active peer networking operations. * * Also sets {@link exchanges} to undefined to prevent future connections. */ async disconnect() { using _disconnecting = this.#lifetime.join("disconnecting"); this.#exchanges = undefined; await MatterAggregateError.allSettled( this.#peers.map(peer => peer.disconnect()), "Error disconnecting peers", ); } async close() { using _closing = this.#lifetime.closing(); for (const peer of this.#peers) { await peer.close(); } this.#observers.close(); } async #openSocket(address: ServerAddressIp, abort: AbortSignal) { const channelType = "type" in address && address.type === "tcp" ? ChannelType.TCP : ChannelType.UDP; let lookupAddress: string | undefined; if (channelType === ChannelType.UDP) { // UDP transports are bound to specific interfaces (IPv4/IPv6) lookupAddress = isIPv6(address.ip) ? "::" : "0.0.0.0"; } const operationalInterface = this.#peerContext.exchanges.interfaceFor(channelType, lookupAddress); if (operationalInterface === undefined) { throw new NetworkUnreachableError( `No ${channelType.toUpperCase()} interface available for address ${address.ip}`, ); } // Plumb the abort signal into openChannel so an aborted TCP connect is destroyed at the // socket level — prevents an orphan TcpChannel being registered after the caller gives up. // The openChannel path may reject with an abort error before Abort.race's listener wins // the EventTarget callback ordering; convert that to undefined to preserve the // race-returns-undefined-on-abort contract that PeerConnection relies on. if (abort.aborted) return undefined; try { const result = await Abort.race(abort, operationalInterface.openChannel(address, { abort })); return result === undefined ? undefined : result; } catch (e) { if (abort.aborted) return undefined; throw e; } } addKnownPeer(descriptor: PeerDescriptor) { let peer = this.get(descriptor.address); if (peer === undefined) { peer = new Peer(descriptor, this.#peerContext); this.#applyDefaultPreference(peer); this.#peers.add(peer); return peer; } // A known peer's discovery data, session parameters and TCP flag are live, so the descriptor only fills what is // unknown; its address and CATs replace the peer's if (descriptor.operationalAddress !== undefined) { peer.descriptor.operationalAddress = descriptor.operationalAddress; } if (descriptor.caseAuthenticatedTags !== undefined) { peer.descriptor.caseAuthenticatedTags = descriptor.caseAuthenticatedTags; } if (descriptor.discoveryData !== undefined) { peer.descriptor.discoveryData = { ...descriptor.discoveryData, ...peer.descriptor.discoveryData }; } if (peer.descriptor.reportedSessionParameters === undefined) { peer.descriptor.reportedSessionParameters = descriptor.reportedSessionParameters; } if (peer.descriptor.tcpUnsupported === undefined) { peer.descriptor.tcpUnsupported = descriptor.tcpUnsupported; } return peer; } } function operationalAddressOf(session: Session): OperationalAddress | undefined { if (session.isClosed || !isIpNetworkChannel(session.channel)) { return; } // TCP incoming connections have an ephemeral remote port — not the peer's listening port if (session.channel.transportChannel.type === ChannelType.TCP) { return; } return { ...session.channel.networkAddress, type: "udp" }; }