/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { DeepPartial, Duration, Hours, isObject, merge as mergeObjects, Millis, Minutes, Seconds, } from "@matter/general"; /** * Parameters that control network timing for Matter sessions controlled by matter.js. */ export interface PeerTimingParameters { /** * Overall timeout for establishing connections. * * This timeout applies to the process of establishing a new session with a peer. It only applies if you do not * override and do not supply an {@link AbortSignal}. */ defaultConnectionTimeout: Duration; /** * The longest time between retries. * * This is the longest period between packets between MRP retries when we attempt initial contact. One Sigma1 is * also retransmitted until both `MRP.MAX_TRANSMISSIONS` transmissions and this time since the first one have * passed; then we continue with a fresh Sigma1 on a new exchange. */ maxDelayBetweenInitialContactRetries: Duration; /** * Wait time before trying the next address. * * We run addresses in parallel but delay the time between the initial attempt for each address by this amount. */ delayBeforeNextAddress: Duration; /** * Delay following a low-level network error. * * We use this when we could not contact the peer. * * Note that this includes MRP timeouts *except* for an unacknowledged Sigma1 on initial contact; in that case we * continue with a fresh Sigma1 at once. */ delayAfterNetworkError: Duration; /** * Delay following report of general error from peer. * * We use this when we have successfully contacted a peer but could not negotiate a new session. */ delayAfterPeerError: Duration; /** * Delay for an unhandled exception. * * Any error that occurs here should be considered internal or should use one of above delays instead. */ delayAfterUnhandledError: Duration; /** * Minimum interval between kick signals reaching the connection handler. * * Rapid-fire kicks (e.g. from mDNS bursts) are throttled at the observable level so only one * signal per interval is delivered. */ kickThrottleInterval: Duration; /** * Minimum number of MRP retransmissions before a kick may restart the exchange. * * Gives the peer a fair chance to respond before aborting. A kick arriving while Sigma1 to the address has been * retransmitted fewer than this many times, counted across fresh Sigma1 messages, is suppressed. */ kickMinRetransmissions: number; /** * Minimum time a kick-initiated restart must shave off the next retransmission to be worthwhile. * * Restarting resets MRP backoff to its base interval, so it only helps once backoff has grown well * beyond that base. A kick whose restart would save less than this is suppressed — for an idle/sleepy * peer the base interval is already large, so a restart gains nothing and needlessly tears down the * in-flight exchange. */ kickMinRestartSaving: Duration; /** * Per-trigger cooldowns for kick-initiated CASE exchange restarts. * * When a kick fires, the current handshake exchange is aborted and restarted from scratch. * These cooldowns prevent restarts from happening too frequently. */ kickRestartCooldown: { /** Cooldown after a restart triggered by DNS-SD address change. */ addressChange: Duration; /** Cooldown after a restart triggered by an explicit {@link Peer.kick} call. */ connect: Duration; }; /** * Delay after detecting mDNS address changes before probing the session. * * Address changes can arrive in bursts (e.g. Thread network rekey). We wait this long after the last * change before checking whether the session's IP is still valid. */ addressChangeStabilizationDelay: Duration; /** * Probe cooldown range for address-change probes. * * When mDNS keeps reporting the session IP as gone but probes succeed, the cooldown grows * using a Fibonacci-like sequence from {@link minimum} to {@link maximum}. The cooldown * resets on a probe failure or a subscription-liveness scare, not on a mere address change. * * Probes are also suppressed while the session is actively receiving data — the cooldown * is measured from whichever is more recent: the last probe or the last received message. */ addressChangeProbeCooldown: { /** Minimum delay before sending a probe (first two probes use this). */ minimum: Duration; /** Upper bound — cooldown stops growing beyond this. */ maximum: Duration; }; } const complete = Symbol("complete-timing-parameters"); interface Internal extends PeerTimingParameters { [complete]: true; } export function PeerTimingParameters(options?: DeepPartial) { if (options && (options as Internal)[complete]) { return options as PeerTimingParameters; } return applyOverrides(PeerTimingParameters.defaults, options); } /** * Layer overrides onto a complete parameter set. Grouped parameters merge field-wise, so overriding one member of a * group leaves its siblings at their prior value rather than dropping them. */ function applyOverrides(base: PeerTimingParameters, overrides?: DeepPartial) { const result = { ...base } as Record; if (overrides) { for (const key of Object.keys(overrides)) { const value = (overrides as Record)[key]; if (value === undefined) { continue; } const current = result[key]; result[key] = isObject(current) && isObject(value) ? mergeObjects(current, value) : value; } } result[complete] = true; return result as unknown as PeerTimingParameters; } export namespace PeerTimingParameters { /** * Merge overrides on top of a base set of timing parameters. * * Unlike calling {@link PeerTimingParameters} directly (which merges on top of {@link defaults}), this starts from * an arbitrary base. Only override fields that are explicitly defined and non-undefined are applied. */ export function merge( base: PeerTimingParameters, overrides: DeepPartial, ): PeerTimingParameters { return applyOverrides(base, overrides); } const maxInitialContactRetryInterval = Minutes(2); // TODO - tune these export const defaults: PeerTimingParameters = { defaultConnectionTimeout: Seconds(90), maxDelayBetweenInitialContactRetries: maxInitialContactRetryInterval, // We assume 30s processing time on peer for single Sigma actions, so give one IP a bit of time // to have a chance before potentially adding a load with a second try delayBeforeNextAddress: Seconds(45), delayAfterNetworkError: Seconds(15), delayAfterPeerError: Minutes(5), delayAfterUnhandledError: Minutes(2), kickThrottleInterval: Seconds(3), kickMinRetransmissions: 2, kickMinRestartSaving: Millis(maxInitialContactRetryInterval / 2), kickRestartCooldown: { addressChange: Minutes(30), connect: Minutes(10), }, addressChangeStabilizationDelay: Seconds(10), addressChangeProbeCooldown: { minimum: Minutes(10), maximum: Hours(24), }, }; }