LCOV - code coverage report
Current view: top level - model - MockServerData.cpp (source / functions) Coverage Total Hit
Test: lcov.info Lines: 77.6 % 76 59
Test Date: 2026-10-04 17:31:08 Functions: 77.8 % 9 7

            Line data    Source code
       1              : /*
       2              :  ___________________________________________
       3              : |    _     ___                        _     |
       4              : |   | |   |__ \                      | |    |
       5              : |   | |__    ) |__ _  __ _  ___ _ __ | |_   |
       6              : |   | '_ \  / // _` |/ _` |/ _ \ '_ \| __|  |  HTTP/2 AGENT FOR MOCK TESTING
       7              : |   | | | |/ /| (_| | (_| |  __/ | | | |_   |  Version 0.0.z
       8              : |   |_| |_|____\__,_|\__, |\___|_| |_|\__|  |  https://github.com/testillano/h2agent
       9              : |                     __/ |                 |
      10              : |                    |___/                  |
      11              : |___________________________________________|
      12              : 
      13              : Licensed under the MIT License <http://opensource.org/licenses/MIT>.
      14              : SPDX-License-Identifier: MIT
      15              : Copyright (c) 2021 Eduardo Ramos
      16              : 
      17              : Permission is hereby  granted, free of charge, to any  person obtaining a copy
      18              : of this software and associated  documentation files (the "Software"), to deal
      19              : in the Software  without restriction, including without  limitation the rights
      20              : to  use, copy,  modify, merge,  publish, distribute,  sublicense, and/or  sell
      21              : copies  of  the Software,  and  to  permit persons  to  whom  the Software  is
      22              : furnished to do so, subject to the following conditions:
      23              : 
      24              : The above copyright notice and this permission notice shall be included in all
      25              : copies or substantial portions of the Software.
      26              : 
      27              : THE SOFTWARE  IS PROVIDED "AS  IS", WITHOUT WARRANTY  OF ANY KIND,  EXPRESS OR
      28              : IMPLIED,  INCLUDING BUT  NOT  LIMITED TO  THE  WARRANTIES OF  MERCHANTABILITY,
      29              : FITNESS FOR  A PARTICULAR PURPOSE AND  NONINFRINGEMENT. IN NO EVENT  SHALL THE
      30              : AUTHORS  OR COPYRIGHT  HOLDERS  BE  LIABLE FOR  ANY  CLAIM,  DAMAGES OR  OTHER
      31              : LIABILITY, WHETHER IN AN ACTION OF  CONTRACT, TORT OR OTHERWISE, ARISING FROM,
      32              : OUT OF OR IN CONNECTION WITH THE SOFTWARE  OR THE USE OR OTHER DEALINGS IN THE
      33              : SOFTWARE.
      34              : */
      35              : 
      36              : #include <string>
      37              : #include <algorithm>
      38              : 
      39              : #include <ert/tracing/Logger.hpp>
      40              : 
      41              : #include <MockServerData.hpp>
      42              : 
      43              : 
      44              : namespace h2agent
      45              : {
      46              : namespace model
      47              : {
      48              : 
      49          290 : void MockServerData::loadEvent(const DataKey &dataKey, const std::string &previousState, const std::string &state, const std::chrono::microseconds &receptionTimestampUs, unsigned int responseStatusCode, const nghttp2::asio_http2::header_map &requestHeaders, const nghttp2::asio_http2::header_map &responseHeaders, DataPart &requestBodyDataPart, const std::string &responseBody, std::uint64_t serverSequence, unsigned int responseDelayMs, bool historyEnabled, const std::string &virtualOriginComingFromMethod, const std::string &virtualOriginComingFromUri) {
      50              : 
      51          290 :     bool maiden{};
      52          290 :     auto events = std::static_pointer_cast<MockServerEventsHistory>(getEvents(dataKey, maiden));
      53              : 
      54          290 :     events->loadEvent(previousState, state, receptionTimestampUs, responseStatusCode, requestHeaders, responseHeaders, requestBodyDataPart, responseBody, serverSequence, responseDelayMs, historyEnabled, virtualOriginComingFromMethod, virtualOriginComingFromUri);
      55              : 
      56          290 :     if (maiden) add(dataKey.getKey(), events); // push the key in the map:
      57              : 
      58          290 :     last_loaded_event_ = std::static_pointer_cast<MockServerEvent>(events->getEvent(1, true /* reverse: last */));
      59          290 : }
      60              : 
      61            0 : bool MockServerData::removeEventByRecvSeq(const DataKey &dataKey, std::uint64_t recvSeq) {
      62              : 
      63            0 :     bool exists{};
      64            0 :     auto events = std::static_pointer_cast<MockServerEventsHistory>(get(dataKey.getKey(), exists));
      65            0 :     if (!exists) return false;
      66              : 
      67            0 :     bool deleted = events->removeEventByRecvSeq(recvSeq);
      68              : 
      69              :     // Cleanup empty map entry:
      70            0 :     if (deleted && events->size() == 0) {
      71            0 :         bool aux{};
      72            0 :         remove(dataKey.getKey(), aux);
      73              :     }
      74              : 
      75            0 :     return deleted;
      76            0 : }
      77              : 
      78            0 : std::shared_ptr<MockEvent> MockServerData::getEventByRecvSeq(const DataKey &dataKey, std::uint64_t recvSeq) {
      79              : 
      80            0 :     bool exists{};
      81            0 :     auto events = std::static_pointer_cast<MockServerEventsHistory>(get(dataKey.getKey(), exists));
      82            0 :     if (!exists) return nullptr;
      83              : 
      84            0 :     return events->getEventByRecvSeq(recvSeq);
      85            0 : }
      86              : 
      87           11 : std::shared_ptr<MockEvent> MockServerData::getEventByUriStartsWith(const std::string &requestMethod, const std::string &uriPrefix, const std::string &eventNumber) const {
      88              : 
      89              :     // Decode the requested position (1..N, or -1 for the latest):
      90           11 :     std::uint64_t uNumber{};
      91           11 :     bool reverse{};
      92           11 :     if (!h2agent::model::string2uint64andSign(eventNumber, uNumber, reverse) || uNumber == 0) {
      93            2 :         LOGDEBUG(ert::tracing::Logger::debug(ert::tracing::Logger::asString("Invalid event number '%s' for URI-prefix server event addressing", eventNumber.c_str()), ERT_FILE_LOCATION));
      94            2 :         return nullptr;
      95              :     }
      96              : 
      97              :     // Collect all events whose key matches 'method' exactly and whose URI starts with 'uriPrefix' (literal),
      98              :     // tagging each with its reception timestamp to build a single chronologically ordered set across keys:
      99              :     struct Entry {
     100              :         std::uint64_t timestampUs;
     101              :         std::shared_ptr<MockEvent> event;
     102              :     };
     103            9 :     std::vector<Entry> entries;
     104              : 
     105            9 :     forEach([&](const mock_events_key_t&, const std::shared_ptr<MockEventsHistory> &history) {
     106           18 :         const auto &key = history->getKey();
     107           25 :         if (key.getMethod() != requestMethod) return;
     108              :         // Literal 'startsWith' (no regex): the prefix is compared verbatim against the normalized URI:
     109           16 :         if (key.getUri().rfind(uriPrefix, 0) != 0) return;
     110              : 
     111            9 :         read_guard_t guard(history->getMutex());
     112           27 :         for (const auto &ev : history->getEvents()) {
     113           54 :             std::uint64_t recTs = std::static_pointer_cast<MockServerEvent>(ev)->getJson()["receptionTimestampUs"].get<std::uint64_t>();
     114           18 :             entries.push_back({recTs, ev});
     115              :         }
     116           27 :     });
     117              : 
     118            9 :     if (entries.empty() || uNumber > entries.size()) return nullptr;
     119              : 
     120            4 :     std::sort(entries.begin(), entries.end(), [](const Entry &a, const Entry &b) {
     121           16 :         return a.timestampUs < b.timestampUs;
     122              :     });
     123              : 
     124              :     // 'reverse' selects from the tail (most recent); otherwise from the head:
     125            4 :     return reverse ? entries[entries.size() - uNumber].event : entries[uNumber - 1].event;
     126            9 : }
     127              : 
     128            4 : std::string MockServerData::getSequence(std::uint64_t fromTimestampUs, std::uint64_t toTimestampUs, const std::string &requestMethod, const std::regex *uriRegex) const {
     129              : 
     130              :     struct Entry {
     131              :         std::uint64_t timestampUs;
     132              :         std::string direction;
     133              :         std::string method;
     134              :         std::string uri;
     135              :     };
     136            4 :     std::vector<Entry> entries;
     137              : 
     138            4 :     forEach([&](const mock_events_key_t&, const std::shared_ptr<MockEventsHistory> &history) {
     139            6 :         const auto &key = history->getKey();
     140            6 :         const std::string &method = key.getMethod();
     141            6 :         const std::string &uri = key.getUri();
     142              : 
     143            7 :         if (!requestMethod.empty() && method != requestMethod) return;
     144            4 :         if (uriRegex && !std::regex_search(uri, *uriRegex)) return;
     145              : 
     146            3 :         read_guard_t guard(history->getMutex());
     147            9 :         for (const auto &ev : history->getEvents()) {
     148            6 :             auto serverEv = std::static_pointer_cast<MockServerEvent>(ev);
     149           12 :             std::uint64_t recTs = serverEv->getJson()["receptionTimestampUs"].get<std::uint64_t>();
     150            6 :             std::uint64_t sendTs = serverEv->getSendingTimestampUs();
     151              : 
     152              :             // Recv entry:
     153            6 :             if ((!fromTimestampUs || recTs >= fromTimestampUs) && (!toTimestampUs || recTs <= toTimestampUs)) {
     154            6 :                 entries.push_back({recTs, "recv", method, uri});
     155              :             }
     156              :             // Send entry:
     157            6 :             if (sendTs && (!fromTimestampUs || sendTs >= fromTimestampUs) && (!toTimestampUs || sendTs <= toTimestampUs)) {
     158            0 :                 entries.push_back({sendTs, "send", method, uri});
     159              :             }
     160            6 :         }
     161           21 :     });
     162              : 
     163            4 :     std::sort(entries.begin(), entries.end(), [](const Entry &a, const Entry &b) {
     164            8 :         return a.timestampUs < b.timestampUs;
     165              :     });
     166              : 
     167            4 :     nlohmann::json result = nlohmann::json::array();
     168           10 :     for (const auto &e : entries) {
     169            6 :         nlohmann::json obj;
     170            6 :         obj["direction"] = e.direction;
     171            6 :         obj["method"] = e.method;
     172            6 :         obj["uri"] = e.uri;
     173            6 :         obj["timestampUs"] = e.timestampUs;
     174            6 :         result.push_back(std::move(obj));
     175            6 :     }
     176              : 
     177            8 :     return result.dump();
     178            4 : }
     179              : 
     180              : }
     181              : }
     182              : 
        

Generated by: LCOV version 2.0-1