/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { ReadResult } from "#action/response/ReadResult.js"; import { IncomingInteractionClientMessenger } from "#interaction/InteractionMessenger.js"; import { Subscription } from "#interaction/Subscription.js"; import { MessageExchange } from "#protocol/MessageExchange.js"; import { ProtocolHandler } from "#protocol/ProtocolHandler.js"; import { SecureSession } from "#session/SecureSession.js"; import { AbortedError, causedBy, Diagnostic, InternalError, Logger } from "@matter/general"; import { DataReport, INTERACTION_PROTOCOL_ID, TlvAttributeReport, TypeFromSchema } from "@matter/types"; import { InputChunk } from "../InputChunk.js"; import { ClientSubscriptions } from "./ClientSubscriptions.js"; const logger = Logger.get("ClientSubscriptionHandler"); /** * A protocol handler that informs {@link ClientSubscriptions} of new exchanges. */ export class ClientSubscriptionHandler implements ProtocolHandler { id = INTERACTION_PROTOCOL_ID; requiresSecureSession = true; #subscriptions: ClientSubscriptions; constructor(subscriptions: ClientSubscriptions) { this.#subscriptions = subscriptions; } async onNewExchange(exchange: MessageExchange) { // During shutdown, reject immediately so the remote device can clean up its subscription state if (this.#subscriptions.isBlocked) { const messenger = new IncomingInteractionClientMessenger(exchange); try { await messenger.sendInvalidSubscription(); } finally { await messenger.close(); } return; } // Track this read so blockNewActivity() can await its completion using _reading = this.#subscriptions.beginReading(); try { await this.#handleExchange(exchange); } catch (error) { // During shutdown the abort signal terminates reads at any point — initial read, chunked reports, // or inside the updated() callback. Only suppress errors that are both (a) during our shutdown // abort and (b) actually caused by an abort — real bugs during shutdown still propagate. if (this.#subscriptions.readingAbortSignal.aborted && causedBy(error, AbortedError)) { logger.debug(exchange.via, "Data report processing aborted during shutdown"); return; } throw error; } } async #handleExchange(exchange: MessageExchange) { const messenger = new IncomingInteractionClientMessenger(exchange); const abort = this.#subscriptions.readingAbortSignal; // Read the initial report — the abort signal lets us terminate promptly during shutdown instead of // waiting for the full (potentially multi-chunk) data report to complete const reports = messenger.readDataReports({ abort }); const initialIteration = await reports.next(); if (initialIteration.done) { throw new InternalError("Exchange initiated with no initial message"); } const initialReport = initialIteration.value; // Ensure there is a subscription ID present const { subscriptionId } = initialReport; if (subscriptionId === undefined) { logger.debug(exchange.via, "Ignoring unsolicited data report with no subscription ID"); try { await messenger.sendInvalidSubscription(); } finally { await messenger.close(); } return; } // Ensure the subscription ID is valid const { session } = exchange.channel; SecureSession.assert(session); const subscription = this.#subscriptions.getPeer(session.peerAddress, subscriptionId); if (subscription === undefined) { logger.info( exchange.via, "Ignoring data report for unknown subscription ID", Diagnostic.strong(Subscription.idStrOf(subscriptionId)), ); try { await messenger.sendInvalidSubscription(subscriptionId); } finally { await messenger.close(); } return; } // Pass the data to the recipient try { subscription.isReading = true; // Announce the report (data or keepalive) as it starts arriving, not on completion — a multi-chunk // report may stream for a while, and liveness is proven the moment the peer starts sending. this.#subscriptions.reportStarted.emit(session); // If this is just a ping, only reset the timeout if (!initialReport.attributeReports?.length && !initialReport.eventReports?.length) { // An empty keepalive never reaches updated(), so the subscriber learns of it separately. subscription.request.keepaliveReceived?.(); // Read the next report to trigger success message sent out const ending = await reports.next(); if (!ending.done) { logger.warn( exchange.via, "Unexpected data reports after empty report", Diagnostic.strong(Subscription.idStrOf(subscriptionId)), ); for await (const _chunk of reports); // Read over these extraneous reports } } else { if (subscription.request.updated) { await subscription.request.updated(processReports(initialReport, reports, messenger)); } else { // It doesn't make sense to have the callback undefined, but we allow it in the type because they may // be handled by intermediate interactables. So we handle the case here too, but just iterate and throw // away the reports for await (const _chunk of reports); } } } finally { subscription.isReading = false; subscription.timeoutAt = undefined; this.#subscriptions.resetTimer(); await messenger.close(); } } async close() {} } /** * Convert incoming data reports into a {@link ReadResult}. * * Parses incoming reports and validates subscription IDs. */ async function* processReports( initialReport: DataReport, otherReports: AsyncIterable, messenger: IncomingInteractionClientMessenger, ): ReadResult { const leftOverData = new Array>(); yield InputChunk(initialReport, leftOverData); const { subscriptionId } = initialReport; for await (const report of otherReports) { const { subscriptionId: reportSubscriptionId } = report; if (reportSubscriptionId === undefined) { logger.debug(messenger.exchange.via, "Ignoring data report with missing subscription id"); await messenger.sendInvalidSubscription(reportSubscriptionId); return; } if (reportSubscriptionId !== subscriptionId) { logger.debug( messenger.exchange.via, "Ignoring data report for incorrect subscription id", Diagnostic.strong(Subscription.idStrOf(reportSubscriptionId)), "expected", Subscription.idStrOf(subscriptionId), ); await messenger.sendInvalidSubscription(reportSubscriptionId); return; } yield InputChunk(report, leftOverData); } }