/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { PeerAddress } from "#peer/PeerAddress.js"; import type { MRP } from "#protocol/MRP.js"; import { Diagnostic, Duration, Environment, Environmental, Logger, MatterError, merge, Millis, Seconds, Semaphore, } from "@matter/general"; import { Peer } from "./Peer.js"; const logger = Logger.get("NetworkProfiles"); /** * Thrown when a named network profile does not exist. */ export class UnknownNetworkProfileError extends MatterError {} export interface ConcreteNetworkProfile { /** * The ID of the NetworkProfile used to register with {@link NetworkProfiles}. */ id: string; /** * A {@link Semaphore} that limits communications for this particular profile. */ semaphore: Semaphore; /** * Additive margin applied to MRP retransmission backoff for exchanges on this profile. * * Compensates for network latency not reflected in the peer's advertised SAI/SII. Combined * with the local "own" profile margin via max at send time. */ additionalMrpDelay: Duration; /** * The additive MRP margins for this profile, by traffic class. * * Precomputed because it is read on the send path; {@link MRP.Margins.bdx} is {@link additionalMrpDelay} unless * the medium needs bulk transfer paced differently from normal messaging. */ mrpMargins: MRP.Margins; } /** * A single logical Matter networking segment. * * A "network profile" is a logical grouping of nodes that share rate limits. By default matter.js selects a network * based on medium, falling back to {@link NetworkProfiles.conservative} if the medium is unknown. * * TODO - record latency and packet loss to support dynamic rate limits */ export interface NetworkProfile extends ConcreteNetworkProfile { /** * An additional profile that applies only to the establishment of new CASE sessions. */ connect?: ConcreteNetworkProfile; /** * An additional profile that applies only to address probe reads. */ probeAddress?: ConcreteNetworkProfile; } /** * Controls how we interact with peers based on the network in which the peer resides. */ export class NetworkProfiles { #networks = new Map(); #defaults: NetworkProfiles.Templates; constructor(options?: NetworkProfiles.Options) { this.#defaults = { ...NetworkProfiles.defaults, ...options, }; } set defaults(options: NetworkProfiles.PartialOptions) { // Cached profiles derive from the previous defaults. this.#networks.clear(); // Layer onto current instance defaults so partial options compose across calls. const base = { ...this.#defaults }; for (const key of Object.keys(options) as (keyof NetworkProfiles.Templates)[]) { const override = options[key]; if (override !== undefined) { const { connect, probeAddress, ...rest } = override; const merged = merge(base[key], rest); if (connect !== undefined) { merged.connect = merge(base[key].connect ?? {}, connect) as NetworkProfiles.ConcreteLimits; } if (probeAddress !== undefined) { merged.probeAddress = merge( base[key].probeAddress ?? {}, probeAddress, ) as NetworkProfiles.ConcreteLimits; } base[key] = merged; } } this.#defaults = base; } static [Environmental.create](env: Environment) { const instance = new this(); env.set(NetworkProfiles, instance); return instance; } select(peer: Peer, id?: string) { if (id !== undefined) { return this.get(id); } return this.forPeer(peer); } /** * Retrieve the named network profile. * * @param id one of the standard {@link NetworkProfiles.Templates} or any previously configured identifier */ get(id: string) { const network = this.#networks.get(id); if (network) { return network; } if (!Object.hasOwn(this.#defaults, id)) { throw new UnknownNetworkProfileError(`Network profile ${id} is not configured`); } return this.configure(id, this.#defaults[id as keyof NetworkProfiles.Templates]); } configure(id: string, limits: NetworkProfiles.Limits, parentDelay?: Duration) { const additionalMrpDelay = limits.additionalMrpDelay ?? parentDelay ?? Millis(0); const network: NetworkProfile = { id, semaphore: new Semaphore(`network semaphore ${id}`, limits.exchanges, limits.delay, limits.timeout), additionalMrpDelay, mrpMargins: { messaging: additionalMrpDelay, bdx: limits.bdxAdditionalMrpDelay ?? additionalMrpDelay, }, }; if (limits.connect) { network.connect = this.configure( `${id}:connect`, { ...limits.connect, connect: undefined, probeAddress: undefined }, additionalMrpDelay, ); } if (limits.probeAddress) { network.probeAddress = this.configure( `${id}:probe`, { ...limits.probeAddress, connect: undefined, probeAddress: undefined }, additionalMrpDelay, ); } logger.info( "Configure profile", id, Diagnostic.dict({ ...limits, connect: undefined, probeAddress: undefined }), ); this.#networks.set(id, network); return network; } forPeer(peer: Peer) { const pp = peer.physicalProperties; let id: string, defaults: NetworkProfiles.Limits; if (PeerAddress.isGroup(peer.address)) { id = "group"; defaults = this.#defaults.fast; } else if (pp === undefined) { id = "unknown"; defaults = this.#defaults.unknown; } else if (pp.threadActive || (pp.threadActive === undefined && pp.supportsThread)) { if (pp.threadChannel) { id = `thread:${pp.threadChannel}`; } else { id = "thread"; } defaults = this.#defaults.thread; } else if ( pp.wifiActive || // No operational-medium data: a WiFi-capable node conservatively gets the WiFi margin. (pp.wifiActive === undefined && pp.ethernetActive === undefined && pp.supportsWifi) ) { id = "wifi"; defaults = this.#defaults.wifi; } else if ( pp.supportsEthernet || // We have data but no Network Commissioning cluster, means "other means" (!pp.supportsWifi && !pp.supportsEthernet && !pp.supportsThread && pp.rootEndpointServerList.length > 0) ) { id = "fast"; defaults = this.#defaults.fast; } else { id = "unknown"; defaults = this.#defaults.unknown; } return this.#networks.get(id) ?? this.configure(id, defaults); } } export namespace NetworkProfiles { export interface Options extends Partial {} /** * Like {@link Options} but allows partially specifying individual profiles, including nested connect limits. */ export type PartialOptions = { [K in keyof Templates]?: Partial> & { connect?: Partial; probeAddress?: Partial; }; }; export interface ConcreteLimits { /** * Maximum number of concurrent exchanges. */ exchanges: number; /** * Delay between new exchanges. */ delay?: Duration; /** * Maximum timeout for one exchange before trying the next in any case. */ timeout?: Duration; /** * Additive MRP retransmission margin for this medium. Defaults to 0 unless the template sets one. */ additionalMrpDelay?: Duration; } /** * Parameters that control exchange throttling for a specific medium. */ export interface Limits extends ConcreteLimits { /** * {@link additionalMrpDelay} for bulk transfer (BDX) exchanges, which sustain many round trips over one path. * * Defaults to {@link additionalMrpDelay}. Values above roughly 7s are inert: a BDX retransmission interval is * capped so the whole schedule fits the peer's response budget. */ bdxAdditionalMrpDelay?: Duration; /** * Overrides specifically for establishing new sessions. * * If present, any values here act as limits specifically for CASE session establishment. */ connect?: ConcreteLimits; /** * Overrides specifically for address probe reads. * * If present, any values here act as limits specifically for probing peer addresses. */ probeAddress?: ConcreteLimits; } /** * Standard profiles, selected automatically based on transfer medium. */ export interface Templates { /** * Limit for "fast" networks. * * We use this value for ethernet. */ fast: Limits; /** * Limit for WiFi networks. * * Matches {@link fast} concurrency but adds an MRP retransmission margin: WiFi power-save can delay delivery * beyond the peer's advertised SAI/SII, and retransmitting too eagerly wastes airtime. */ wifi: Limits; /** * Limit for thread networks, by channel. * * Each channel has a separate network, plus an additional one for devices that do not report their channel. * If the device indicates thread is disabled then we use {@link fast}. */ thread: Limits; /** * Conservative limits used as the base for constrained networks. */ conservative: Limits; /** * Limits for peers with unknown physical properties. * * Defaults to {@link conservative}. Note that this template is automatically overwritten at startup for * device nodes based on the node's network capabilities. Manually setting this may have no effect. To * adjust limits, override {@link fast}, {@link thread} or {@link conservative} instead. */ unknown: Limits; /** * Limit for "unlimited" networks. * * Interactions only use this profile if you specify explicitly. */ unlimited: Limits; /** * Priority profile for interactions with an await-mode (LIT) ICD. * * Applies no concurrency throttle, so a check-in-triggered interaction is not queued behind bulk traffic and * can land inside the peer's brief active window. MRP timing is unaffected: it derives from the peer's medium * profile, so selecting this profile swaps only the throttle semaphore. */ icdLit: Limits; } /** * The fallback used for unknown network IDs or mediums. */ export const conservative: Limits = { exchanges: 4, delay: Millis(100), additionalMrpDelay: Seconds(1.5), connect: { exchanges: 4, timeout: Seconds(10), // Release slot for connections after 15s latest }, probeAddress: { exchanges: 2, timeout: Seconds(15), }, }; export const defaults: Templates = { unlimited: { exchanges: Infinity, additionalMrpDelay: Millis(0) }, icdLit: { exchanges: Infinity, additionalMrpDelay: Millis(0) }, fast: { exchanges: 200, additionalMrpDelay: Millis(0) }, wifi: { exchanges: 200, additionalMrpDelay: Seconds(1) }, thread: conservative, conservative, unknown: conservative, }; }