Matter SDK Coverage Report
Current view: top level - app - InteractionModelEngine.h (source / functions) Coverage Total Hit
Test: SHA:b879ecb8e99e175eea0a293a888bda853da2b19c Lines: 96.6 % 29 28
Test Date: 2025-01-17 19:00:11 Functions: 93.8 % 16 15

            Line data    Source code
       1              : /*
       2              :  *
       3              :  *    Copyright (c) 2020-2021 Project CHIP Authors
       4              :  *    All rights reserved.
       5              :  *
       6              :  *    Licensed under the Apache License, Version 2.0 (the "License");
       7              :  *    you may not use this file except in compliance with the License.
       8              :  *    You may obtain a copy of the License at
       9              :  *
      10              :  *        http://www.apache.org/licenses/LICENSE-2.0
      11              :  *
      12              :  *    Unless required by applicable law or agreed to in writing, software
      13              :  *    distributed under the License is distributed on an "AS IS" BASIS,
      14              :  *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      15              :  *    See the License for the specific language governing permissions and
      16              :  *    limitations under the License.
      17              :  */
      18              : 
      19              : /**
      20              :  *    @file
      21              :  *      This file defines objects for a CHIP Interaction Data model Engine which handle unsolicited IM message, and
      22              :  *      manage different kinds of IM client and handlers.
      23              :  *
      24              :  */
      25              : 
      26              : #pragma once
      27              : 
      28              : // TODO(#32628): Remove the CHIPCore.h header when the esp32 build is correctly fixed
      29              : #include <lib/core/CHIPCore.h>
      30              : 
      31              : #include <access/AccessControl.h>
      32              : #include <app/AppConfig.h>
      33              : #include <app/AttributePathParams.h>
      34              : #include <app/CommandHandlerImpl.h>
      35              : #include <app/CommandResponseSender.h>
      36              : #include <app/CommandSender.h>
      37              : #include <app/ConcreteAttributePath.h>
      38              : #include <app/ConcreteCommandPath.h>
      39              : #include <app/ConcreteEventPath.h>
      40              : #include <app/DataVersionFilter.h>
      41              : #include <app/EventPathParams.h>
      42              : #include <app/MessageDef/AttributeReportIBs.h>
      43              : #include <app/MessageDef/ReportDataMessage.h>
      44              : #include <app/ReadClient.h>
      45              : #include <app/ReadHandler.h>
      46              : #include <app/StatusResponse.h>
      47              : #include <app/SubscriptionResumptionSessionEstablisher.h>
      48              : #include <app/SubscriptionsInfoProvider.h>
      49              : #include <app/TimedHandler.h>
      50              : #include <app/WriteClient.h>
      51              : #include <app/WriteHandler.h>
      52              : #include <app/data-model-provider/OperationTypes.h>
      53              : #include <app/data-model-provider/Provider.h>
      54              : #include <app/icd/server/ICDServerConfig.h>
      55              : #include <app/reporting/Engine.h>
      56              : #include <app/reporting/ReportScheduler.h>
      57              : #include <app/util/attribute-metadata.h>
      58              : #include <app/util/basic-types.h>
      59              : #include <lib/core/CHIPCore.h>
      60              : #include <lib/support/CodeUtils.h>
      61              : #include <lib/support/DLLUtil.h>
      62              : #include <lib/support/LinkedList.h>
      63              : #include <lib/support/Pool.h>
      64              : #include <lib/support/logging/CHIPLogging.h>
      65              : #include <messaging/ExchangeContext.h>
      66              : #include <messaging/ExchangeMgr.h>
      67              : #include <messaging/Flags.h>
      68              : #include <protocols/Protocols.h>
      69              : #include <protocols/interaction_model/Constants.h>
      70              : #include <system/SystemPacketBuffer.h>
      71              : 
      72              : #include <app/CASESessionManager.h>
      73              : 
      74              : #if CHIP_CONFIG_ENABLE_ICD_SERVER
      75              : #include <app/icd/server/ICDManager.h> // nogncheck
      76              : #endif                                 // CHIP_CONFIG_ENABLE_ICD_SERVER
      77              : 
      78              : namespace chip {
      79              : namespace app {
      80              : 
      81              : /**
      82              :  * @class InteractionModelEngine
      83              :  *
      84              :  * @brief This is a singleton hosting all CHIP unsolicited message processing and managing interaction model related clients and
      85              :  * handlers
      86              :  *
      87              :  */
      88              : class InteractionModelEngine : public Messaging::UnsolicitedMessageHandler,
      89              :                                public Messaging::ExchangeDelegate,
      90              :                                private DataModel::ActionContext,
      91              :                                public CommandResponseSender::Callback,
      92              :                                public CommandHandlerImpl::Callback,
      93              :                                public ReadHandler::ManagementCallback,
      94              :                                public FabricTable::Delegate,
      95              :                                public SubscriptionsInfoProvider,
      96              :                                public TimedHandlerDelegate,
      97              :                                public WriteHandlerDelegate
      98              : {
      99              : public:
     100              :     /**
     101              :      * @brief Retrieve the singleton Interaction Model Engine.
     102              :      *
     103              :      *  @return  A pointer to the shared InteractionModel Engine
     104              :      *
     105              :      */
     106              :     static InteractionModelEngine * GetInstance(void);
     107              : 
     108              :     /**
     109              :      * Spec 8.5.1 A publisher SHALL always ensure that every fabric the node is commissioned into can create at least three
     110              :      * subscriptions to the publisher and that each subscription SHALL support at least 3 attribute/event paths.
     111              :      */
     112              :     static constexpr size_t kMinSupportedSubscriptionsPerFabric = 3;
     113              :     static constexpr size_t kMinSupportedPathsPerSubscription   = 3;
     114              :     static constexpr size_t kMinSupportedPathsPerReadRequest    = 9;
     115              :     static constexpr size_t kMinSupportedReadRequestsPerFabric  = 1;
     116              :     static constexpr size_t kReadHandlerPoolSize                = CHIP_IM_MAX_NUM_SUBSCRIPTIONS + CHIP_IM_MAX_NUM_READS;
     117              : 
     118              :     // TODO: Per spec, the above numbers should be 3, 3, 9, 1, however, we use a lower limit to reduce the memory usage and should
     119              :     // fix it when we have reduced the memory footprint of ReadHandlers.
     120              : 
     121              :     InteractionModelEngine(void);
     122              : 
     123              :     /**
     124              :      *  Initialize the InteractionModel Engine.
     125              :      *
     126              :      *  @param[in]    apExchangeMgr    A pointer to the ExchangeManager object.
     127              :      *  @param[in]    apFabricTable    A pointer to the FabricTable object.
     128              :      *  @param[in]    apCASESessionMgr An optional pointer to a CASESessionManager (used for re-subscriptions).
     129              :      *
     130              :      */
     131              :     CHIP_ERROR Init(Messaging::ExchangeManager * apExchangeMgr, FabricTable * apFabricTable,
     132              :                     reporting::ReportScheduler * reportScheduler, CASESessionManager * apCASESessionMgr = nullptr,
     133              :                     SubscriptionResumptionStorage * subscriptionResumptionStorage = nullptr);
     134              : 
     135              :     void Shutdown();
     136              : 
     137              : #if CHIP_CONFIG_ENABLE_ICD_SERVER
     138              :     void SetICDManager(ICDManager * manager) { mICDManager = manager; };
     139              : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
     140              : 
     141         1465 :     Messaging::ExchangeManager * GetExchangeManager(void) const { return mpExchangeMgr; }
     142              : 
     143              :     /**
     144              :      * Returns a pointer to the CASESessionManager. This can return nullptr if one wasn't
     145              :      * provided in the call to Init().
     146              :      */
     147            1 :     CASESessionManager * GetCASESessionManager() const { return mpCASESessionMgr; }
     148              : 
     149              : #if CHIP_CONFIG_ENABLE_READ_CLIENT
     150              :     /**
     151              :      * Tears down an active subscription.
     152              :      *
     153              :      * @retval #CHIP_ERROR_KEY_NOT_FOUND If the subscription is not found.
     154              :      * @retval #CHIP_NO_ERROR On success.
     155              :      */
     156              :     CHIP_ERROR ShutdownSubscription(const ScopedNodeId & aPeerNodeId, SubscriptionId aSubscriptionId);
     157              : 
     158              :     /**
     159              :      * Tears down active subscriptions for a given peer node ID.
     160              :      */
     161              :     void ShutdownSubscriptions(FabricIndex aFabricIndex, NodeId aPeerNodeId);
     162              : 
     163              :     /**
     164              :      * Tears down all active subscriptions for a given fabric.
     165              :      */
     166              :     void ShutdownSubscriptions(FabricIndex aFabricIndex);
     167              : 
     168              :     /**
     169              :      * Tears down all active subscriptions.
     170              :      */
     171              :     void ShutdownAllSubscriptions();
     172              : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
     173              : 
     174              :     uint32_t GetNumActiveReadHandlers() const;
     175              :     uint32_t GetNumActiveReadHandlers(ReadHandler::InteractionType type) const;
     176              : 
     177              :     /**
     178              :      * Returns the number of active readhandlers with a specific type on a specific fabric.
     179              :      */
     180              :     uint32_t GetNumActiveReadHandlers(ReadHandler::InteractionType type, FabricIndex fabricIndex) const;
     181              : 
     182              :     uint32_t GetNumActiveWriteHandlers() const;
     183              : 
     184              :     /**
     185              :      * Returns the handler at a particular index within the active handler list.
     186              :      */
     187              :     ReadHandler * ActiveHandlerAt(unsigned int aIndex);
     188              : 
     189              :     /**
     190              :      * Returns the write handler at a particular index within the active handler list.
     191              :      */
     192              :     WriteHandler * ActiveWriteHandlerAt(unsigned int aIndex);
     193              : 
     194         5058 :     reporting::Engine & GetReportingEngine() { return mReportingEngine; }
     195              : 
     196          292 :     reporting::ReportScheduler * GetReportScheduler() { return mReportScheduler; }
     197              : 
     198              :     void ReleaseAttributePathList(SingleLinkedListNode<AttributePathParams> *& aAttributePathList);
     199              : 
     200              :     CHIP_ERROR PushFrontAttributePathList(SingleLinkedListNode<AttributePathParams> *& aAttributePathList,
     201              :                                           AttributePathParams & aAttributePath);
     202              : 
     203              :     // If a concrete path indicates an attribute that is also referenced by a wildcard path in the request,
     204              :     // the path SHALL be removed from the list.
     205              :     void RemoveDuplicateConcreteAttributePath(SingleLinkedListNode<AttributePathParams> *& aAttributePaths);
     206              : 
     207              :     void ReleaseEventPathList(SingleLinkedListNode<EventPathParams> *& aEventPathList);
     208              : 
     209              :     CHIP_ERROR PushFrontEventPathParamsList(SingleLinkedListNode<EventPathParams> *& aEventPathList, EventPathParams & aEventPath);
     210              : 
     211              :     void ReleaseDataVersionFilterList(SingleLinkedListNode<DataVersionFilter> *& aDataVersionFilterList);
     212              : 
     213              :     CHIP_ERROR PushFrontDataVersionFilterList(SingleLinkedListNode<DataVersionFilter> *& aDataVersionFilterList,
     214              :                                               DataVersionFilter & aDataVersionFilter);
     215              : 
     216              :     /*
     217              :      * Register an application callback to be notified of notable events when handling reads/subscribes.
     218              :      */
     219              :     void RegisterReadHandlerAppCallback(ReadHandler::ApplicationCallback * mpApplicationCallback)
     220              :     {
     221              :         mpReadHandlerApplicationCallback = mpApplicationCallback;
     222              :     }
     223              :     void UnregisterReadHandlerAppCallback() { mpReadHandlerApplicationCallback = nullptr; }
     224              : 
     225              :     // TimedHandlerDelegate implementation
     226              :     void OnTimedInteractionFailed(TimedHandler * apTimedHandler) override;
     227              :     void OnTimedInvoke(TimedHandler * apTimedHandler, Messaging::ExchangeContext * apExchangeContext,
     228              :                        const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload) override;
     229              :     void OnTimedWrite(TimedHandler * apTimedHandler, Messaging::ExchangeContext * apExchangeContext,
     230              :                       const PayloadHeader & aPayloadHeader, System::PacketBufferHandle && aPayload) override;
     231              : 
     232              :     // WriteHandlerDelegate implementation
     233              :     bool HasConflictWriteRequests(const WriteHandler * apWriteHandler, const ConcreteAttributePath & apath) override;
     234              : 
     235              : #if CHIP_CONFIG_ENABLE_READ_CLIENT
     236              :     /**
     237              :      *  Activate the idle subscriptions.
     238              :      *
     239              :      *  When subscribing to ICD and liveness timeout reached, the read client will move to `InactiveICDSubscription` state and
     240              :      * resubscription can be triggered via OnActiveModeNotification().
     241              :      */
     242              :     void OnActiveModeNotification(ScopedNodeId aPeer);
     243              : 
     244              :     /**
     245              :      *  Used to notify when a peer becomes LIT ICD or vice versa.
     246              :      *
     247              :      *  ReadClient will call this function when it finds any updates of the OperatingMode attribute from ICD management
     248              :      * cluster. The application doesn't need to call this function, usually.
     249              :      */
     250              :     void OnPeerTypeChange(ScopedNodeId aPeer, ReadClient::PeerType aType);
     251              : 
     252              :     /**
     253              :      * Add a read client to the internally tracked list of weak references. This list is used to
     254              :      * correctly dispatch unsolicited reports to the right matching handler by subscription ID.
     255              :      */
     256              :     void AddReadClient(ReadClient * apReadClient);
     257              : 
     258              :     /**
     259              :      * Remove a read client from the internally tracked list of weak references.
     260              :      */
     261              :     void RemoveReadClient(ReadClient * apReadClient);
     262              : 
     263              :     /**
     264              :      * Test to see if a read client is in the actively tracked list.
     265              :      */
     266              :     bool InActiveReadClientList(ReadClient * apReadClient);
     267              : 
     268              :     /**
     269              :      * Return the number of active read clients being tracked by the engine.
     270              :      */
     271              :     size_t GetNumActiveReadClients();
     272              : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
     273              : 
     274              :     /**
     275              :      * Returns the number of dirty subscriptions. Including the subscriptions that are generating reports.
     276              :      */
     277              :     size_t GetNumDirtySubscriptions() const;
     278              : 
     279              :     /**
     280              :      * Select the oldest (and the one that exceeds the per subscription resource minimum if there are any) read handler on the
     281              :      * fabric with the given fabric index. Evict it when the fabric uses more resources than the per fabric quota or aForceEvict is
     282              :      * true.
     283              :      *
     284              :      * @retval Whether we have evicted a subscription.
     285              :      */
     286              :     bool TrimFabricForSubscriptions(FabricIndex aFabricIndex, bool aForceEvict);
     287              : 
     288              :     /**
     289              :      * Select a read handler and abort the read transaction if the fabric is using more resources (number of paths or number of read
     290              :      * handlers) then we guaranteed.
     291              :      *
     292              :      * - The youngest oversized read handlers will be chosen first.
     293              :      * - If there are no oversized read handlers, the youngest read handlers will be chosen.
     294              :      *
     295              :      * @retval Whether we have evicted a read transaction.
     296              :      */
     297              :     bool TrimFabricForRead(FabricIndex aFabricIndex);
     298              : 
     299              :     /**
     300              :      * Returns the minimal value of guaranteed subscriptions per fabic. UINT16_MAX will be returned if current app is configured to
     301              :      * use heap for the object pools used by interaction model engine.
     302              :      *
     303              :      * @retval the minimal value of guaranteed subscriptions per fabic.
     304              :      */
     305              :     uint16_t GetMinGuaranteedSubscriptionsPerFabric() const;
     306              : 
     307              :     // virtual method from FabricTable::Delegate
     308              :     void OnFabricRemoved(const FabricTable & fabricTable, FabricIndex fabricIndex) override;
     309              : 
     310          258 :     SubscriptionResumptionStorage * GetSubscriptionResumptionStorage() { return mpSubscriptionResumptionStorage; };
     311              : 
     312              :     CHIP_ERROR ResumeSubscriptions();
     313              : 
     314              :     bool SubjectHasActiveSubscription(FabricIndex aFabricIndex, NodeId subjectID) override;
     315              : 
     316              :     bool SubjectHasPersistedSubscription(FabricIndex aFabricIndex, NodeId subjectID) override;
     317              : 
     318              :     bool FabricHasAtLeastOneActiveSubscription(FabricIndex aFabricIndex) override;
     319              : 
     320              : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     321              :     /**
     322              :      * @brief Function decrements the number of subscriptions to resume counter - mNumOfSubscriptionsToResume.
     323              :      *        This should be called after we have completed a re-subscribe attempt on a persisted subscription wether the attempt
     324              :      *        was succesful or not.
     325              :      */
     326              :     void DecrementNumSubscriptionsToResume();
     327              : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     328              : 
     329              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     330              :     //
     331              :     // Get direct access to the underlying read handler pool
     332              :     //
     333              :     auto & GetReadHandlerPool() { return mReadHandlers; }
     334              : 
     335              :     //
     336              :     // Override the maximal capacity of the fabric table only for interaction model engine
     337              :     //
     338              :     // If -1 is passed in, no override is instituted and default behavior resumes.
     339              :     //
     340              :     void SetConfigMaxFabrics(int32_t sz) { mMaxNumFabricsOverride = sz; }
     341              : 
     342              :     //
     343              :     // Override the maximal capacity of the underlying read handler pool to mimic
     344              :     // out of memory scenarios in unit-tests. You need to SetConfigMaxFabrics to make GetGuaranteedReadRequestsPerFabric
     345              :     // working correctly.
     346              :     //
     347              :     // If -1 is passed in, no override is instituted and default behavior resumes.
     348              :     //
     349              :     void SetHandlerCapacityForReads(int32_t sz) { mReadHandlerCapacityForReadsOverride = sz; }
     350              :     void SetHandlerCapacityForSubscriptions(int32_t sz) { mReadHandlerCapacityForSubscriptionsOverride = sz; }
     351              : 
     352              :     //
     353              :     // Override the maximal capacity of the underlying attribute path pool and event path pool to mimic
     354              :     // out of paths exhausted scenarios in unit-tests.
     355              :     //
     356              :     // If -1 is passed in, no override is instituted and default behavior resumes.
     357              :     //
     358              :     void SetPathPoolCapacityForReads(int32_t sz) { mPathPoolCapacityForReadsOverride = sz; }
     359              :     void SetPathPoolCapacityForSubscriptions(int32_t sz) { mPathPoolCapacityForSubscriptionsOverride = sz; }
     360              : 
     361              :     //
     362              :     // We won't limit the handler used per fabric on platforms that are using heap for memory pools, so we introduces a flag to
     363              :     // enforce such check based on the configured size. This flag is used for unit tests only, there is another compare time flag
     364              :     // CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK for stress tests.
     365              :     //
     366              :     void SetForceHandlerQuota(bool forceHandlerQuota) { mForceHandlerQuota = forceHandlerQuota; }
     367              : 
     368              : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
     369              :     //
     370              :     // Override the subscription timeout resumption retry interval seconds. The default retry interval will be
     371              :     // 300s + GetFibonacciForIndex(retry_times) * 300s, which is too long for unit-tests.
     372              :     //
     373              :     // If -1 is passed in, no override is instituted and default behavior resumes.
     374              :     //
     375              :     void SetSubscriptionTimeoutResumptionRetryIntervalSeconds(int32_t seconds)
     376              :     {
     377              :         mSubscriptionResumptionRetrySecondsOverride = seconds;
     378              :     }
     379              : #endif
     380              : 
     381              :     //
     382              :     // When testing subscriptions using the high-level APIs in src/controller/ReadInteraction.h,
     383              :     // they don't provide for the ability to shut down those subscriptions after they've been established.
     384              :     //
     385              :     // So for the purposes of unit tests, add a helper here to shut down and clean-up all active handlers.
     386              :     //
     387              :     void ShutdownActiveReads()
     388              :     {
     389              : #if CHIP_CONFIG_ENABLE_READ_CLIENT
     390              :         for (auto * readClient = mpActiveReadClientList; readClient != nullptr;)
     391              :         {
     392              :             readClient->mpImEngine = nullptr;
     393              :             auto * tmpClient       = readClient->GetNextClient();
     394              :             readClient->SetNextClient(nullptr);
     395              :             readClient->Close(CHIP_NO_ERROR);
     396              :             readClient = tmpClient;
     397              :         }
     398              : 
     399              :         //
     400              :         // After that, we just null out our tracker.
     401              :         //
     402              :         mpActiveReadClientList = nullptr;
     403              : #endif // CHIP_CONFIG_ENABLE_READ_CLIENT
     404              : 
     405              :         mReadHandlers.ReleaseAll();
     406              :     }
     407              : #endif
     408              : 
     409              :     DataModel::Provider * GetDataModelProvider() const;
     410              : 
     411              :     // MUST NOT be used while the interaction model engine is running as interaction
     412              :     // model functionality (e.g. active reads/writes/subscriptions) rely on data model
     413              :     // state
     414              :     //
     415              :     // Returns the old data model provider value.
     416              :     DataModel::Provider * SetDataModelProvider(DataModel::Provider * model);
     417              : 
     418              : private:
     419              :     /* DataModel::ActionContext implementation */
     420            0 :     Messaging::ExchangeContext * CurrentExchange() override { return mCurrentExchange; }
     421              : 
     422              :     friend class reporting::Engine;
     423              :     friend class TestCommandInteraction;
     424              :     friend class TestInteractionModelEngine;
     425              :     friend class SubscriptionResumptionSessionEstablisher;
     426              :     using Status = Protocols::InteractionModel::Status;
     427              : 
     428              :     void OnDone(CommandResponseSender & apResponderObj) override;
     429              :     void OnDone(CommandHandlerImpl & apCommandObj) override;
     430              :     void OnDone(ReadHandler & apReadObj) override;
     431              : 
     432              :     void TryToResumeSubscriptions();
     433              : 
     434         1461 :     ReadHandler::ApplicationCallback * GetAppCallback() override { return mpReadHandlerApplicationCallback; }
     435              : 
     436        15882 :     InteractionModelEngine * GetInteractionModelEngine() override { return this; }
     437              : 
     438              :     CHIP_ERROR OnUnsolicitedMessageReceived(const PayloadHeader & payloadHeader, ExchangeDelegate *& newDelegate) override;
     439              : 
     440              :     /**
     441              :      * Called when Interaction Model receives a Command Request message.
     442              :      */
     443              :     Status OnInvokeCommandRequest(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
     444              :                                   System::PacketBufferHandle && aPayload, bool aIsTimedInvoke);
     445              :     CHIP_ERROR OnMessageReceived(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
     446              :                                  System::PacketBufferHandle && aPayload) override;
     447              :     void OnResponseTimeout(Messaging::ExchangeContext * ec) override;
     448              : 
     449              :     /**
     450              :      * This parses the attribute path list to ensure it is well formed. If so, for each path in the list, it will expand to a list
     451              :      * of concrete paths and walk each path to check if it has privileges to read that attribute.
     452              :      *
     453              :      * If there is AT LEAST one "existent path" (as the spec calls it) that has sufficient privilege, aHasValidAttributePath
     454              :      * will be set to true. Otherwise, it will be set to false.
     455              :      *
     456              :      * aRequestedAttributePathCount will be updated to reflect the number of attribute paths in the request.
     457              :      *
     458              :      *
     459              :      */
     460              :     CHIP_ERROR ParseAttributePaths(const Access::SubjectDescriptor & aSubjectDescriptor,
     461              :                                    AttributePathIBs::Parser & aAttributePathListParser, bool & aHasValidAttributePath,
     462              :                                    size_t & aRequestedAttributePathCount);
     463              : 
     464              :     /**
     465              :      * This parses the event path list to ensure it is well formed. If so, for each path in the list, it will expand to a list
     466              :      * of concrete paths and walk each path to check if it has privileges to read that event.
     467              :      *
     468              :      * If there is AT LEAST one "existent path" (as the spec calls it) that has sufficient privilege, aHasValidEventPath
     469              :      * will be set to true. Otherwise, it will be set to false.
     470              :      *
     471              :      * aRequestedEventPathCount will be updated to reflect the number of event paths in the request.
     472              :      */
     473              :     CHIP_ERROR ParseEventPaths(const Access::SubjectDescriptor & aSubjectDescriptor, EventPathIBs::Parser & aEventPathListParser,
     474              :                                bool & aHasValidEventPath, size_t & aRequestedEventPathCount);
     475              : 
     476              :     /**
     477              :      * Called when Interaction Model receives a Read Request message.  Errors processing
     478              :      * the Read Request are handled entirely within this function.  If the
     479              :      * status returned is not Status::Success, the caller will send a status
     480              :      * response message with that status.
     481              :      */
     482              :     Status OnReadInitialRequest(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
     483              :                                 System::PacketBufferHandle && aPayload, ReadHandler::InteractionType aInteractionType);
     484              : 
     485              :     /**
     486              :      * Called when Interaction Model receives a Write Request message.  Errors processing
     487              :      * the Write Request are handled entirely within this function. If the
     488              :      * status returned is not Status::Success, the caller will send a status
     489              :      * response message with that status.
     490              :      */
     491              :     Status OnWriteRequest(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
     492              :                           System::PacketBufferHandle && aPayload, bool aIsTimedWrite);
     493              : 
     494              :     /**
     495              :      * Called when Interaction Model receives a Timed Request message.  Errors processing
     496              :      * the Timed Request are handled entirely within this function. The caller pre-sets status to failure and the callee is
     497              :      * expected to set it to success if it does not want an automatic status response message to be sent.
     498              :      */
     499              :     CHIP_ERROR OnTimedRequest(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
     500              :                               System::PacketBufferHandle && aPayload, Protocols::InteractionModel::Status & aStatus);
     501              : 
     502              :     /**This function handles processing of un-solicited ReportData messages on the client, which can
     503              :      * only occur post subscription establishment
     504              :      */
     505              :     Status OnUnsolicitedReportData(Messaging::ExchangeContext * apExchangeContext, const PayloadHeader & aPayloadHeader,
     506              :                                    System::PacketBufferHandle && aPayload);
     507              : 
     508              :     void DispatchCommand(CommandHandlerImpl & apCommandObj, const ConcreteCommandPath & aCommandPath,
     509              :                          TLV::TLVReader & apPayload) override;
     510              : 
     511              :     Protocols::InteractionModel::Status ValidateCommandCanBeDispatched(const DataModel::InvokeRequest & request) override;
     512              : 
     513              :     bool HasActiveRead();
     514              : 
     515          136 :     inline size_t GetPathPoolCapacityForReads() const
     516              :     {
     517              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     518          136 :         return (mPathPoolCapacityForReadsOverride == -1) ? CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS
     519          136 :                                                          : static_cast<size_t>(mPathPoolCapacityForReadsOverride);
     520              : #else
     521              :         return CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS;
     522              : #endif
     523              :     }
     524              : 
     525          890 :     inline size_t GetReadHandlerPoolCapacityForReads() const
     526              :     {
     527              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     528          890 :         return (mReadHandlerCapacityForReadsOverride == -1) ? CHIP_IM_MAX_NUM_READS
     529          890 :                                                             : static_cast<size_t>(mReadHandlerCapacityForReadsOverride);
     530              : #else
     531              :         return CHIP_IM_MAX_NUM_READS;
     532              : #endif
     533              :     }
     534              : 
     535          237 :     inline size_t GetPathPoolCapacityForSubscriptions() const
     536              :     {
     537              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     538          237 :         return (mPathPoolCapacityForSubscriptionsOverride == -1) ? CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS
     539          237 :                                                                  : static_cast<size_t>(mPathPoolCapacityForSubscriptionsOverride);
     540              : #else
     541              :         return CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS;
     542              : #endif
     543              :     }
     544              : 
     545          237 :     inline size_t GetReadHandlerPoolCapacityForSubscriptions() const
     546              :     {
     547              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     548          237 :         return (mReadHandlerCapacityForSubscriptionsOverride == -1)
     549          237 :             ? CHIP_IM_MAX_NUM_SUBSCRIPTIONS
     550          237 :             : static_cast<size_t>(mReadHandlerCapacityForSubscriptionsOverride);
     551              : #else
     552              :         return CHIP_IM_MAX_NUM_SUBSCRIPTIONS;
     553              : #endif
     554              :     }
     555              : 
     556          855 :     inline uint8_t GetConfigMaxFabrics() const
     557              :     {
     558              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     559          855 :         return (mMaxNumFabricsOverride == -1) ? CHIP_CONFIG_MAX_FABRICS : static_cast<uint8_t>(mMaxNumFabricsOverride);
     560              : #else
     561              :         return CHIP_CONFIG_MAX_FABRICS;
     562              : #endif
     563              :     }
     564              : 
     565          822 :     inline size_t GetGuaranteedReadRequestsPerFabric() const
     566              :     {
     567          822 :         return GetReadHandlerPoolCapacityForReads() / GetConfigMaxFabrics();
     568              :     }
     569              : 
     570              :     /**
     571              :      * Verify and ensure (by killing oldest read handlers that make the resources used by the current fabric exceed the fabric
     572              :      * quota)
     573              :      * - If the subscription uses resources within the per subscription limit, this function will always success by evicting
     574              :      * existing subscriptions.
     575              :      * - If the subscription uses more than per subscription limit, this function will return PATHS_EXHAUSTED if we are running out
     576              :      * of paths.
     577              :      *
     578              :      * After the checks above, we will try to ensure we have a free Readhandler for processing the subscription.
     579              :      *
     580              :      * @retval true when we have enough resources for the incoming subscription, false if not.
     581              :      */
     582              :     bool EnsureResourceForSubscription(FabricIndex aFabricIndex, size_t aRequestedAttributePathCount,
     583              :                                        size_t aRequestedEventPathCount);
     584              : 
     585              :     /**
     586              :      * Verify and ensure (by killing oldest read handlers that make the resources used by the current fabric exceed the fabric
     587              :      * quota) the resources for handling a new read transaction with the given resource requirments.
     588              :      * - PASE sessions will be counted in a virtual fabric (i.e. kInvalidFabricIndex will be consided as a "valid" fabric in this
     589              :      * function)
     590              :      * - If the existing resources can serve this read transaction, this function will return Status::Success.
     591              :      * - or if the resources used by read transactions in the fabric index meets the per fabric resource limit (i.e. 9 paths & 1
     592              :      * read) after accepting this read request, this function will always return Status::Success by evicting existing read
     593              :      * transactions from other fabrics which are using more than the guaranteed minimum number of read.
     594              :      * - or if the resources used by read transactions in the fabric index will exceed the per fabric resource limit (i.e. 9 paths &
     595              :      * 1 read) after accepting this read request, this function will return a failure status without evicting any existing
     596              :      * transaction.
     597              :      * - However, read transactions on PASE sessions won't evict any existing read transactions when we have already commissioned
     598              :      * CHIP_CONFIG_MAX_FABRICS fabrics on the device.
     599              :      *
     600              :      * @retval Status::Success: The read transaction can be accepted.
     601              :      * @retval Status::Busy: The remaining resource is insufficient to handle this read request, and the accessing fabric for this
     602              :      * read request will use more resources than we guaranteed, the client is expected to retry later.
     603              :      * @retval Status::PathsExhausted: The attribute / event path pool is exhausted, and the read request is requesting more
     604              :      * resources than we guaranteed.
     605              :      */
     606              :     Status EnsureResourceForRead(FabricIndex aFabricIndex, size_t aRequestedAttributePathCount, size_t aRequestedEventPathCount);
     607              : 
     608              :     /**
     609              :      * Helper for various ShutdownSubscriptions functions.  The subscriptions
     610              :      * that match all the provided arguments will be shut down.
     611              :      */
     612              :     void ShutdownMatchingSubscriptions(const Optional<FabricIndex> & aFabricIndex = NullOptional,
     613              :                                        const Optional<NodeId> & aPeerNodeId       = NullOptional);
     614              : 
     615              :     Status CheckCommandExistence(const ConcreteCommandPath & aCommandPath);
     616              :     Status CheckCommandAccess(const DataModel::InvokeRequest & aRequest);
     617              :     Status CheckCommandFlags(const DataModel::InvokeRequest & aRequest);
     618              : 
     619              :     /**
     620              :      * Check if the given attribute path is a valid path in the data model provider.
     621              :      */
     622              :     bool IsExistentAttributePath(const ConcreteAttributePath & path);
     623              : 
     624              :     static void ResumeSubscriptionsTimerCallback(System::Layer * apSystemLayer, void * apAppState);
     625              : 
     626              :     template <typename T, size_t N>
     627              :     void ReleasePool(SingleLinkedListNode<T> *& aObjectList, ObjectPool<SingleLinkedListNode<T>, N> & aObjectPool);
     628              :     template <typename T, size_t N>
     629              :     CHIP_ERROR PushFront(SingleLinkedListNode<T> *& aObjectList, T & aData, ObjectPool<SingleLinkedListNode<T>, N> & aObjectPool);
     630              : 
     631              :     Messaging::ExchangeManager * mpExchangeMgr = nullptr;
     632              : 
     633              : #if CHIP_CONFIG_ENABLE_ICD_SERVER
     634              :     ICDManager * mICDManager = nullptr;
     635              : #endif // CHIP_CONFIG_ENABLE_ICD_SERVER
     636              : 
     637              :     ObjectPool<CommandResponseSender, CHIP_IM_MAX_NUM_COMMAND_HANDLER> mCommandResponderObjs;
     638              :     ObjectPool<TimedHandler, CHIP_IM_MAX_NUM_TIMED_HANDLER> mTimedHandlers;
     639              :     WriteHandler mWriteHandlers[CHIP_IM_MAX_NUM_WRITE_HANDLER];
     640              :     reporting::Engine mReportingEngine;
     641              :     reporting::ReportScheduler * mReportScheduler = nullptr;
     642              : 
     643              :     static constexpr size_t kReservedHandlersForReads = kMinSupportedReadRequestsPerFabric * (CHIP_CONFIG_MAX_FABRICS);
     644              :     static constexpr size_t kReservedPathsForReads    = kMinSupportedPathsPerReadRequest * kReservedHandlersForReads;
     645              : 
     646              : #if !CHIP_SYSTEM_CONFIG_POOL_USE_HEAP
     647              :     static_assert(CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS >=
     648              :                       CHIP_CONFIG_MAX_FABRICS * (kMinSupportedPathsPerSubscription * kMinSupportedSubscriptionsPerFabric),
     649              :                   "CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS is too small to match the requirements of spec 8.5.1");
     650              :     static_assert(CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS >=
     651              :                       CHIP_CONFIG_MAX_FABRICS * (kMinSupportedReadRequestsPerFabric * kMinSupportedPathsPerReadRequest),
     652              :                   "CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS is too small to match the requirements of spec 8.5.1");
     653              :     static_assert(CHIP_IM_MAX_NUM_SUBSCRIPTIONS >= CHIP_CONFIG_MAX_FABRICS * kMinSupportedSubscriptionsPerFabric,
     654              :                   "CHIP_IM_MAX_NUM_SUBSCRIPTIONS is too small to match the requirements of spec 8.5.1");
     655              :     static_assert(CHIP_IM_MAX_NUM_READS >= CHIP_CONFIG_MAX_FABRICS * kMinSupportedReadRequestsPerFabric,
     656              :                   "CHIP_IM_MAX_NUM_READS is too small to match the requirements of spec 8.5.1");
     657              : #endif
     658              : 
     659              :     ObjectPool<SingleLinkedListNode<AttributePathParams>,
     660              :                CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS + CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS>
     661              :         mAttributePathPool;
     662              :     ObjectPool<SingleLinkedListNode<EventPathParams>,
     663              :                CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS + CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS>
     664              :         mEventPathPool;
     665              :     ObjectPool<SingleLinkedListNode<DataVersionFilter>,
     666              :                CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_READS + CHIP_IM_SERVER_MAX_NUM_PATH_GROUPS_FOR_SUBSCRIPTIONS>
     667              :         mDataVersionFilterPool;
     668              : 
     669              :     ObjectPool<ReadHandler, CHIP_IM_MAX_NUM_READS + CHIP_IM_MAX_NUM_SUBSCRIPTIONS> mReadHandlers;
     670              : 
     671              : #if CHIP_CONFIG_ENABLE_READ_CLIENT
     672              :     ReadClient * mpActiveReadClientList = nullptr;
     673              : #endif
     674              : 
     675              :     ReadHandler::ApplicationCallback * mpReadHandlerApplicationCallback = nullptr;
     676              : 
     677              : #if CONFIG_BUILD_FOR_HOST_UNIT_TEST
     678              :     int mReadHandlerCapacityForSubscriptionsOverride = -1;
     679              :     int mPathPoolCapacityForSubscriptionsOverride    = -1;
     680              : 
     681              :     int mReadHandlerCapacityForReadsOverride = -1;
     682              :     int mPathPoolCapacityForReadsOverride    = -1;
     683              : 
     684              :     int mMaxNumFabricsOverride = -1;
     685              : 
     686              :     // We won't limit the handler used per fabric on platforms that are using heap for memory pools, so we introduces a flag to
     687              :     // enforce such check based on the configured size. This flag is used for unit tests only, there is another compare time flag
     688              :     // CHIP_CONFIG_IM_FORCE_FABRIC_QUOTA_CHECK for stress tests.
     689              :     bool mForceHandlerQuota = false;
     690              : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
     691              :     int mSubscriptionResumptionRetrySecondsOverride = -1;
     692              : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS && CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
     693              : #endif // CONFIG_BUILD_FOR_HOST_UNIT_TEST
     694              : 
     695              : #if CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     696              :     /**
     697              :      * mNumOfSubscriptionsToResume tracks the number of subscriptions that the device will try to resume at its next resumption
     698              :      * attempt. At boot up, the attempt will be at the highest min interval of all the subscriptions to resume.
     699              :      * When the subscription timeout resumption feature is present, after the boot up attempt, the next attempt will be determined
     700              :      * by ComputeTimeSecondsTillNextSubscriptionResumption.
     701              :      */
     702              :     int8_t mNumOfSubscriptionsToResume = 0;
     703              : #if CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
     704              :     bool HasSubscriptionsToResume();
     705              :     uint32_t ComputeTimeSecondsTillNextSubscriptionResumption();
     706              :     uint32_t mNumSubscriptionResumptionRetries = 0;
     707              :     bool mSubscriptionResumptionScheduled      = false;
     708              : #endif // CHIP_CONFIG_SUBSCRIPTION_TIMEOUT_RESUMPTION
     709              : #endif // CHIP_CONFIG_PERSIST_SUBSCRIPTIONS
     710              : 
     711              :     FabricTable * mpFabricTable;
     712              : 
     713              :     CASESessionManager * mpCASESessionMgr = nullptr;
     714              : 
     715              :     SubscriptionResumptionStorage * mpSubscriptionResumptionStorage = nullptr;
     716              : 
     717              :     DataModel::Provider * mDataModelProvider      = nullptr;
     718              :     Messaging::ExchangeContext * mCurrentExchange = nullptr;
     719              : 
     720              :     enum class State : uint8_t
     721              :     {
     722              :         kUninitialized, // The object has not been initialized.
     723              :         kInitializing,  // Initial setup is in progress (e.g. setting up mpExchangeMgr).
     724              :         kInitialized    // The object has been fully initialized and is ready for use.
     725              :     };
     726              :     State mState = State::kUninitialized;
     727              : 
     728              :     // Changes the current exchange context of a InteractionModelEngine to a given context
     729              :     class CurrentExchangeValueScope
     730              :     {
     731              :     public:
     732         1588 :         CurrentExchangeValueScope(InteractionModelEngine & engine, Messaging::ExchangeContext * context) : mEngine(engine)
     733              :         {
     734         1588 :             mEngine.mCurrentExchange = context;
     735         1588 :         }
     736              : 
     737         1588 :         ~CurrentExchangeValueScope() { mEngine.mCurrentExchange = nullptr; }
     738              : 
     739              :     private:
     740              :         InteractionModelEngine & mEngine;
     741              :     };
     742              : };
     743              : 
     744              : } // namespace app
     745              : } // namespace chip
        

Generated by: LCOV version 2.0-1