diff --git a/.clang-tidy b/.clang-tidy index b8ebb841f..069b62dc6 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -4,6 +4,7 @@ Checks: "-*, bugprone-assert-side-effect, bugprone-bad-signal-to-kill-thread, bugprone-bool-pointer-implicit-conversion, + bugprone-capturing-this-in-member-variable, bugprone-casting-through-void, bugprone-chained-comparison, bugprone-compare-pointer-to-member-virtual-function, @@ -23,6 +24,7 @@ Checks: "-*, bugprone-lambda-function-name, bugprone-macro-parentheses, bugprone-macro-repeated-side-effects, + bugprone-misleading-setter-of-reference, bugprone-misplaced-operator-in-strlen-in-alloc, bugprone-misplaced-pointer-arithmetic-in-alloc, bugprone-misplaced-widening-cast, @@ -64,6 +66,7 @@ Checks: "-*, bugprone-terminating-continue, bugprone-throw-keyword-missing, bugprone-too-small-loop-variable, + bugprone-unchecked-optional-access, bugprone-undefined-memory-manipulation, bugprone-undelegated-constructor, bugprone-unhandled-exception-at-new, @@ -82,6 +85,7 @@ Checks: "-*, cppcoreguidelines-pro-type-static-cast-downcast, cppcoreguidelines-rvalue-reference-param-not-moved, cppcoreguidelines-use-default-member-init, + cppcoreguidelines-use-enum-class, cppcoreguidelines-virtual-class-destructor, hicpp-ignored-remove-result, llvm-namespace-comment, @@ -105,8 +109,10 @@ Checks: "-*, modernize-use-emplace, modernize-use-equals-default, modernize-use-equals-delete, + modernize-use-nodiscard, modernize-use-override, modernize-use-ranges, + modernize-use-scoped-lock, modernize-use-starts-ends-with, modernize-use-std-numbers, modernize-use-using, @@ -118,6 +124,7 @@ Checks: "-*, performance-move-constructor-init, performance-no-automatic-move, performance-trivially-destructible, + readability-ambiguous-smartptr-reset-call, readability-avoid-nested-conditional-operator, readability-avoid-return-with-void-value, readability-braces-around-statements, @@ -128,9 +135,9 @@ Checks: "-*, readability-duplicate-include, readability-else-after-return, readability-enum-initial-value, + readability-identifier-naming, readability-implicit-bool-conversion, readability-inconsistent-declaration-parameter-name, - readability-identifier-naming, readability-make-member-function-const, readability-math-missing-parentheses, readability-misleading-indentation, @@ -149,6 +156,11 @@ Checks: "-*, " CheckOptions: + bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true + bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc + + misc-include-cleaner.IgnoreHeaders: '.*/(detail|impl)/.*;.*(expected|unexpected).*;.*ranges_lower_bound\.h;time.h;stdlib.h;__chrono/.*;fmt/chrono.h;boost/uuid/uuid_hash.hpp' + readability-braces-around-statements.ShortStatementLines: 2 readability-identifier-naming.MacroDefinitionCase: UPPER_CASE readability-identifier-naming.ClassCase: CamelCase @@ -183,9 +195,6 @@ CheckOptions: readability-identifier-naming.ProtectedMemberSuffix: _ readability-identifier-naming.PublicMemberSuffix: "" readability-identifier-naming.FunctionIgnoredRegexp: ".*tag_invoke.*" - bugprone-unsafe-functions.ReportMoreUnsafeFunctions: true - bugprone-unused-return-value.CheckedReturnTypes: ::std::error_code;::std::error_condition;::std::errc - misc-include-cleaner.IgnoreHeaders: '.*/(detail|impl)/.*;.*(expected|unexpected).*;.*ranges_lower_bound\.h;time.h;stdlib.h;__chrono/.*;fmt/chrono.h;boost/uuid/uuid_hash.hpp' HeaderFilterRegex: '^.*/(src|tests)/.*\.(h|hpp)$' WarningsAsErrors: "*" diff --git a/.github/actions/create-issue/action.yml b/.github/actions/create-issue/action.yml deleted file mode 100644 index 325058007..000000000 --- a/.github/actions/create-issue/action.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Create an issue -description: Create an issue - -inputs: - title: - description: Issue title - required: true - body: - description: Issue body - required: true - labels: - description: Comma-separated list of labels - required: true - default: "bug" - assignees: - description: Comma-separated list of assignees - required: true - default: "godexsoft,kuznetsss,PeterChen13579,mathbunnyru" - -outputs: - created_issue_id: - description: Created issue id - value: ${{ steps.create_issue.outputs.created_issue }} - -runs: - using: composite - steps: - - name: Create an issue - id: create_issue - shell: bash - env: - ISSUE_BODY: ${{ inputs.body }} - ISSUE_ASSIGNEES: ${{ inputs.assignees }} - ISSUE_LABELS: ${{ inputs.labels }} - ISSUE_TITLE: ${{ inputs.title }} - run: | - echo -e "${ISSUE_BODY}" > issue.md - gh issue create \ - --assignee "${ISSUE_ASSIGNEES}" \ - --label "${ISSUE_LABELS}" \ - --title "${ISSUE_TITLE}" \ - --body-file ./issue.md \ - > create_issue.log - created_issue="$(sed 's|.*/||' create_issue.log)" - echo "created_issue=$created_issue" >> $GITHUB_OUTPUT - rm create_issue.log issue.md diff --git a/.github/dependabot.yml b/.github/dependabot.yml index a7fe15d47..6f8e2ae1c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -78,19 +78,6 @@ updates: prefix: "ci: [DEPENDABOT] " target-branch: develop - - package-ecosystem: github-actions - directory: .github/actions/create-issue/ - schedule: - interval: weekly - day: monday - time: "04:00" - timezone: Etc/GMT - reviewers: - - XRPLF/clio-dev-team - commit-message: - prefix: "ci: [DEPENDABOT] " - target-branch: develop - - package-ecosystem: github-actions directory: .github/actions/git-common-ancestor/ schedule: diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 56eaa300d..6e0a8c3e0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -15,7 +15,6 @@ on: - ".github/actions/**" - "!.github/actions/build-docker-image/**" - - "!.github/actions/create-issue/**" - CMakeLists.txt - conanfile.py diff --git a/.github/workflows/check-libxrpl.yml b/.github/workflows/check-libxrpl.yml index 55c8695e6..b85e53adb 100644 --- a/.github/workflows/check-libxrpl.yml +++ b/.github/workflows/check-libxrpl.yml @@ -33,6 +33,9 @@ jobs: with: enable_ccache: false + - name: Print build environment + uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Update libXRPL version requirement run: | sed -i.bak -E "s|'xrpl/[a-zA-Z0-9\\.\\-]+'|'xrpl/${{ github.event.client_payload.conan_ref }}'|g" conanfile.py @@ -95,14 +98,12 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Create an issue - uses: ./.github/actions/create-issue - env: - GH_TOKEN: ${{ github.token }} + uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c with: - labels: "compatibility,bug" title: "Proposed libXRPL check failed" body: > Clio build or tests failed against `libXRPL ${{ github.event.client_payload.conan_ref }}`. PR: ${{ github.event.client_payload.pr_url }} - Workflow run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/ + labels: "compatibility,bug" + assignees: "godexsoft,kuznetsss,mathbunnyru" diff --git a/.github/workflows/clang-tidy.yml b/.github/workflows/clang-tidy.yml index 59afdbff0..16dc15e24 100644 --- a/.github/workflows/clang-tidy.yml +++ b/.github/workflows/clang-tidy.yml @@ -1,16 +1,22 @@ -name: Clang-tidy check +name: Run clang-tidy on files on: push: branches: [develop] - schedule: - - cron: "0 9 * * 1-5" workflow_dispatch: pull_request: branches: [develop] paths: - .github/workflows/clang-tidy.yml + - CMakeLists.txt + - conanfile.py + - conan.lock + - "cmake/**" + - "src/**" + - "tests/**" + - "benchmarks/**" + - .clang_tidy concurrency: @@ -19,19 +25,34 @@ concurrency: cancel-in-progress: true env: + BUILD_DIR: build + BUILD_TYPE: Debug # Debug so that ASSERTS and such participate in clang-tidy check + + OUTPUT_FILE: clang-tidy-output.txt + DIFF_FILE: clang-tidy-git-diff.txt + ISSUE_FILE: clang-tidy-issue.md + CONAN_PROFILE: clang - LLVM_TOOLS_VERSION: 20 + LLVM_TOOLS_VERSION: 21 defaults: run: shell: bash jobs: - clang_tidy: - if: github.event_name != 'push' || contains(github.event.head_commit.message, 'clang-tidy auto fixes') + determine-files: + if: ${{ github.event_name == 'pull_request' }} + permissions: + contents: read + uses: XRPLF/actions/.github/workflows/determine-tidy-files.yml@12f5dbc98a2260259a66970e57fa4d26fb7f285c + + run-clang-tidy: + name: Run clang tidy + needs: [determine-files] + if: ${{ always() && !cancelled() && (github.event_name != 'pull_request' || needs.determine-files.outputs.cpp_changed_files != '' || needs.determine-files.outputs.clang_tidy_config_changed == 'true') }} runs-on: heavy container: - image: ghcr.io/xrplf/clio-ci:14342e087ceb8b593027198bf9ef06a43833c696 + image: ghcr.io/xrplf/clio-ci:f174b47f4909ae41b80406d836ab52adc39eacc6 permissions: contents: write @@ -40,37 +61,54 @@ jobs: steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - fetch-depth: 0 - name: Prepare runner uses: XRPLF/actions/prepare-runner@90f11ee655d1687824fb8793db770477d52afbab with: enable_ccache: false + - name: Print build environment + uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Run conan uses: ./.github/actions/conan with: + build_dir: ${{ env.BUILD_DIR }} conan_profile: ${{ env.CONAN_PROFILE }} + build_type: ${{ env.BUILD_TYPE }} - name: Run CMake uses: ./.github/actions/cmake with: + build_dir: ${{ env.BUILD_DIR }} conan_profile: ${{ env.CONAN_PROFILE }} + build_type: ${{ env.BUILD_TYPE }} - name: Get number of processors uses: XRPLF/actions/get-nproc@cf0433aa74563aead044a1e395610c96d65a37cf id: nproc - - name: Run clang-tidy (several times) + - name: Run clang tidy continue-on-error: true - id: clang_tidy + id: run_clang_tidy + env: + TARGETS: ${{ (needs.determine-files.outputs.clang_tidy_config_changed != 'true' && github.event_name == 'pull_request') && needs.determine-files.outputs.cpp_changed_files || 'benchmarks src tests' }} run: | - # We run clang-tidy several times, because some fixes may enable new fixes in subsequent runs. - CLANG_TIDY_COMMAND="run-clang-tidy-${{ env.LLVM_TOOLS_VERSION }} -p build -j ${{ steps.nproc.outputs.nproc }} -fix -quiet" - ${CLANG_TIDY_COMMAND} || - ${CLANG_TIDY_COMMAND} || - ${CLANG_TIDY_COMMAND} + set -o pipefail + run-clang-tidy-${{ env.LLVM_TOOLS_VERSION }} -j ${{ steps.nproc.outputs.nproc }} -p "${BUILD_DIR}" -quiet -fix -allow-no-checks ${TARGETS} 2>&1 | tee "${OUTPUT_FILE}" + + - name: Print errors + if: ${{ steps.run_clang_tidy.outcome != 'success' }} + run: | + sed '/error\||/!d' "${OUTPUT_FILE}" + + - name: Upload clang-tidy output + if: ${{ github.event.repository.visibility == 'public' && steps.run_clang_tidy.outcome != 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + path: ${{ env.OUTPUT_FILE }} + archive: false + retention-days: 30 - name: Check for changes id: files_changed @@ -78,24 +116,76 @@ jobs: run: | git diff --exit-code - - name: Fix local includes and clang-format style + - name: Fix style if: ${{ steps.files_changed.outcome != 'success' }} run: | - pre-commit run --all-files fix-local-includes || true - pre-commit run --all-files clang-format || true + pre-commit run --all-files || true - - name: Create an issue - if: ${{ (steps.clang_tidy.outcome != 'success' || steps.files_changed.outcome != 'success') && github.event_name != 'pull_request' }} - id: create_issue - uses: ./.github/actions/create-issue - env: - GH_TOKEN: ${{ github.token }} + - name: Generate git diff + if: ${{ steps.files_changed.outcome != 'success' }} + run: | + git diff | tee "${DIFF_FILE}" + + - name: Upload clang-tidy diff output + if: ${{ github.event.repository.visibility == 'public' && steps.files_changed.outcome != 'success' }} + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - title: "Clang-tidy found bugs in code 🐛" - body: > - Clang-tidy found issues in the code: + path: ${{ env.DIFF_FILE }} + archive: false + retention-days: 30 - List of the issues found: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/ + - name: Write issue header + if: ${{ steps.run_clang_tidy.outcome != 'success' }} + run: | + cat > "${ISSUE_FILE}" < filtered-output.txt || true + + # If filtered output is empty, use original (might be a different error format) + if [ ! -s filtered-output.txt ]; then + cp "${OUTPUT_FILE}" filtered-output.txt + fi + + # Truncate if too large + head -c 60000 filtered-output.txt >> "${ISSUE_FILE}" + if [ "$(wc -c < filtered-output.txt)" -gt 60000 ]; then + echo "" >> "${ISSUE_FILE}" + echo "... (output truncated, see artifacts for full output)" >> "${ISSUE_FILE}" + fi + + rm filtered-output.txt + else + echo "No output file found" >> "${ISSUE_FILE}" + fi + + - name: Append issue footer + if: ${{ steps.run_clang_tidy.outcome != 'success' }} + run: | + cat >> "${ISSUE_FILE}" < + Fixes #${{ steps.create_issue.outputs.issue_number }}. + + Please review and commit clang-tidy fixes. + reviewers: "godexsoft,kuznetsss,mathbunnyru" - name: Fail the job - if: ${{ steps.clang_tidy.outcome != 'success' || steps.files_changed.outcome != 'success' }} - run: exit 1 + if: ${{ steps.run_clang_tidy.outcome != 'success' }} + run: | + echo "Clang-tidy check failed!" + exit 1 diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index ea66c9817..fa328edef 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -31,6 +31,9 @@ jobs: with: enable_ccache: false + - name: Print build environment + uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Create build directory run: mkdir build_docs diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index dc78813f2..fc104ec5d 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -172,12 +172,9 @@ jobs: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - name: Create an issue - uses: ./.github/actions/create-issue - env: - GH_TOKEN: ${{ github.token }} + uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c with: title: "Nightly release failed 🌙" - body: > - Nightly release failed: - - Workflow: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/ + body: "" + labels: "bug" + assignees: "godexsoft,kuznetsss,mathbunnyru" diff --git a/.github/workflows/pre-commit-autoupdate.yml b/.github/workflows/pre-commit-autoupdate.yml index 789fddbcb..5d79fec76 100644 --- a/.github/workflows/pre-commit-autoupdate.yml +++ b/.github/workflows/pre-commit-autoupdate.yml @@ -12,11 +12,11 @@ on: jobs: auto-update: - uses: XRPLF/actions/.github/workflows/pre-commit-autoupdate.yml@a249154199805d6809359fe99fa8ba09dd804e3d + uses: XRPLF/actions/.github/workflows/pre-commit-autoupdate.yml@5e942d61bf32f7557a7c159cfac4712a687b3e3a with: sign_commit: true committer: "Clio CI " - reviewers: "godexsoft,kuznetsss,PeterChen13579,mathbunnyru" + reviewers: "godexsoft,kuznetsss,mathbunnyru" secrets: GPG_PRIVATE_KEY: ${{ secrets.ACTIONS_GPG_PRIVATE_KEY }} GPG_PASSPHRASE: ${{ secrets.ACTIONS_GPG_PASSPHRASE }} diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index e1fb3e2d3..9e25304e1 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -8,7 +8,7 @@ on: jobs: run-hooks: - uses: XRPLF/actions/.github/workflows/pre-commit.yml@9307df762265e15c745ddcdb38a581c989f7f349 + uses: XRPLF/actions/.github/workflows/pre-commit.yml@5e942d61bf32f7557a7c159cfac4712a687b3e3a with: runs_on: heavy container: '{ "image": "ghcr.io/xrplf/clio-pre-commit:14342e087ceb8b593027198bf9ef06a43833c696" }' diff --git a/.github/workflows/reusable-build.yml b/.github/workflows/reusable-build.yml index 1684dcf0a..e4d994f8a 100644 --- a/.github/workflows/reusable-build.yml +++ b/.github/workflows/reusable-build.yml @@ -99,6 +99,9 @@ jobs: with: enable_ccache: ${{ inputs.download_ccache }} + - name: Print build environment + uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Setup conan on macOS if: ${{ runner.os == 'macOS' }} run: ./.github/scripts/conan/init.sh diff --git a/.github/workflows/reusable-test.yml b/.github/workflows/reusable-test.yml index 31b3a30fe..f635d59ad 100644 --- a/.github/workflows/reusable-test.yml +++ b/.github/workflows/reusable-test.yml @@ -68,16 +68,12 @@ jobs: - name: Create an issue if: ${{ steps.run_clio_tests.outcome == 'failure' && endsWith(inputs.conan_profile, 'san') }} - uses: ./.github/actions/create-issue - env: - GH_TOKEN: ${{ github.token }} + uses: XRPLF/actions/create-issue@fbcc16eb7f20dc3199eaf1aed0d3523a5ba9008c with: - labels: "bug" title: "[${{ inputs.conan_profile }}] reported issues" - body: > - Clio tests failed one or more sanitizer checks when built with `${{ inputs.conan_profile }}`. - - Workflow: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/ + body: "Clio tests failed one or more sanitizer checks when built with `${{ inputs.conan_profile }}`." + labels: "bug" + assignees: "godexsoft,kuznetsss,mathbunnyru" - name: Fail the job if clio_tests failed if: ${{ steps.run_clio_tests.outcome == 'failure' }} diff --git a/.github/workflows/sanitizers.yml b/.github/workflows/sanitizers.yml index 3f795b730..2e9a05216 100644 --- a/.github/workflows/sanitizers.yml +++ b/.github/workflows/sanitizers.yml @@ -14,7 +14,6 @@ on: - ".github/actions/**" - "!.github/actions/build-docker-image/**" - - "!.github/actions/create-issue/**" - CMakeLists.txt - conanfile.py diff --git a/.github/workflows/upload-conan-deps.yml b/.github/workflows/upload-conan-deps.yml index 884aefb12..c8ea52ffe 100644 --- a/.github/workflows/upload-conan-deps.yml +++ b/.github/workflows/upload-conan-deps.yml @@ -82,6 +82,9 @@ jobs: with: enable_ccache: false + - name: Print build environment + uses: XRPLF/actions/print-build-env@59dec886e4afb05a1724443af08baccbc045b574 + - name: Setup conan on macOS if: ${{ runner.os == 'macOS' }} run: ./.github/scripts/conan/init.sh diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bda562d68..584c11b47 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -29,7 +29,7 @@ repos: # Autoformat: YAML, JSON, Markdown, etc. - repo: https://github.com/rbubley/mirrors-prettier - rev: c2bc67fe8f8f549cc489e00ba8b45aa18ee713b1 # frozen: v3.8.1 + rev: 515f543f5718ebfd6ce22e16708bb32c68ff96e1 # frozen: v3.8.3 hooks: - id: prettier @@ -40,7 +40,7 @@ repos: exclude: LICENSE.md - repo: https://github.com/hadolint/hadolint - rev: 4e697ba704fd23b2409b947a319c19c3ee54d24f # frozen: v2.14.0 + rev: 57e1618d78fd469a92c1e584e8c9313024656623 # frozen: v2.14.0 hooks: - id: hadolint-docker # hadolint-docker is a special hook that runs hadolint in a Docker container @@ -64,7 +64,7 @@ repos: - id: black - repo: https://github.com/scop/pre-commit-shfmt - rev: e26a818fd47b4f33cefa99035d1265b0849f4b47 # frozen: v3.13.0-1 + rev: 05c1426671b9237fb5e1444dd63aa5731bec0dfb # frozen: v3.13.1-1 hooks: - id: shfmt args: ["-i", "4", "--write"] @@ -94,14 +94,14 @@ repos: language: script - repo: https://github.com/pre-commit/mirrors-clang-format - rev: 07a0f7667439f60724899f6ae288e4a4f572e0e1 # frozen: v22.1.2 + rev: 39233709be54124a7371a50cbfc5325bd4fb9d90 # frozen: v22.1.4 hooks: - id: clang-format args: [--style=file] types: [c++] - - repo: https://github.com/BlankSpruce/gersemi - rev: 79ddf2c9f3a84d766fce4e39fb2f83eac62b34f7 # frozen: 0.26.1 + - repo: https://github.com/BlankSpruce/gersemi-pre-commit + rev: fc2d0aefdd73b719180177a2d4a7a56cef4d3ab6 # frozen: 0.27.2 hooks: - id: gersemi diff --git a/conan.lock b/conan.lock index 4c2c81221..b256432b2 100644 --- a/conan.lock +++ b/conan.lock @@ -1,17 +1,17 @@ { "version": "0.5", "requires": [ - "zlib/1.3.1#b8bc2603263cf7eccbd6e17e66b0ed76%1765850150.075", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "xxhash/0.8.3#681d36a0a6111fc56e5e45ea182c19cc%1765850149.987", - "xrpl/3.1.0#3d408ab8c8020014fa7dd52bc7cc7ea8%1769706825.165", + "xrpl/3.1.3#eabc6838b4553671bdde4b3aa1f8e3e6%1778495466.414", "sqlite3/3.49.1#8631739a4c9b93bd3d6b753bac548a63%1765850149.926", "spdlog/1.17.0#bcbaaf7147bda6ad24ffbd1ac3d7142c%1768312128.781", - "soci/4.0.3#a9f8d773cd33e356b5879a4b0564f287%1765850149.46", + "soci/4.0.3#fe32b9ad5eb47e79ab9e45a68f363945%1774450067.231", "re2/20230301#ca3b241baec15bd31ea9187150e0b333%1765850148.103", "rapidjson/cci.20220822#1b9d8c2256876a154172dc5cfbe447c6%1754325007.656", "protobuf/3.21.12#44ee56c0a6eea0c19aeeaca680370b88%1764175361.456", "openssl/1.1.1w#a8f0792d7c5121b954578a7149d23e03%1756223730.729", - "nudb/2.0.9#0432758a24204da08fee953ec9ea03cb%1769436073.32", + "nudb/2.0.9#11149c73f8f2baff9a0198fe25971fc7%1775040983.408", "minizip/1.2.13#9e87d57804bd372d6d1e32b1871517a3%1754325004.374", "lz4/1.10.0#59fc63cac7f10fbe8e05c7e62c2f3504%1765850143.914", "libuv/1.46.0#dc28c1f653fa197f00db5b577a6f6011%1754325003.592", @@ -25,18 +25,18 @@ "doctest/2.4.11#a4211dfc329a16ba9f280f9574025659%1756234220.819", "date/3.0.4#862e11e80030356b53c2c38599ceb32b%1765850143.772", "cassandra-cpp-driver/2.17.0#bd3934138689482102c265d01288a316%1764175359.611", - "c-ares/1.34.5#5581c2b62a608b40bb85d965ab3ec7c8%1765850144.336", + "c-ares/1.34.6#545240bb1c40e2cacd4362d6b8967650%1774439234.681", "bzip2/1.0.8#c470882369c2d95c5c77e970c0c7e321%1765850143.837", "boost/1.83.0#91d8b1572534d2c334d6790e3c34d0c1%1764175359.61", "benchmark/1.9.4#ce4403f7a24d3e1f907cd9da4b678be4%1754578869.672", "abseil/20230802.1#90ba607d4ee8fb5fb157c3db540671fc%1764175359.429" ], "build_requires": [ - "zlib/1.3.1#b8bc2603263cf7eccbd6e17e66b0ed76%1765850150.075", + "zlib/1.3.1#cac0f6daea041b0ccf42934163defb20%1774439233.809", "protobuf/3.21.12#44ee56c0a6eea0c19aeeaca680370b88%1764175361.456", - "cmake/4.2.0#ae0a44f44a1ef9ab68fd4b3e9a1f8671%1765850153.937", - "cmake/3.31.10#313d16a1aa16bbdb2ca0792467214b76%1765850153.479", - "b2/5.3.3#107c15377719889654eb9a162a673975%1765850144.355" + "cmake/4.3.0#b939a42e98f593fb34d3a8c5cc860359%1774439249.183", + "cmake/3.31.11#f325c933f618a1fcebc1e1c0babfd1ba%1774439246.719", + "b2/5.4.2#ffd6084a119587e70f11cd45d1a386e2%1774439233.447" ], "python_requires": [], "overrides": { @@ -51,10 +51,10 @@ "lz4/1.9.4": [ "lz4/1.10.0" ], - "boost/1.90.0": [ + "boost/[>=1.83.0 <1.91.0]": [ "boost/1.83.0" ], - "sqlite3/3.44.2": [ + "sqlite3/[>=3.44 <4]": [ "sqlite3/3.49.1" ] }, diff --git a/conanfile.py b/conanfile.py index bbfce6e81..ddfdeec4e 100644 --- a/conanfile.py +++ b/conanfile.py @@ -19,7 +19,7 @@ class ClioConan(ConanFile): "openssl/1.1.1w", "protobuf/3.21.12", "spdlog/1.17.0", - "xrpl/3.1.0", + "xrpl/3.1.3", "zlib/1.3.1", ] diff --git a/docker/ci/Dockerfile b/docker/ci/Dockerfile index 9c55f7f29..72ba46b0f 100644 --- a/docker/ci/Dockerfile +++ b/docker/ci/Dockerfile @@ -61,7 +61,7 @@ RUN pip install -q --no-cache-dir \ pre-commit # Install LLVM tools -ARG LLVM_TOOLS_VERSION=20 +ARG LLVM_TOOLS_VERSION=21 RUN echo "deb http://apt.llvm.org/focal/ llvm-toolchain-focal-${LLVM_TOOLS_VERSION} main" >> /etc/apt/sources.list \ && wget --progress=dot:giga -O - https://apt.llvm.org/llvm-snapshot.gpg.key | apt-key add - diff --git a/docker/ci/README.md b/docker/ci/README.md index 0bf559991..b8a37a575 100644 --- a/docker/ci/README.md +++ b/docker/ci/README.md @@ -14,6 +14,7 @@ The image is based on Ubuntu 20.04 and contains: - GDB 17.1 - gh 2.83.2 - git-cliff 2.11.0 +- LLVM Tools 21 - mold 2.40.4 - Ninja 1.13.2 - Python 3.8 diff --git a/src/app/VerifyConfig.hpp b/src/app/VerifyConfig.hpp index e7422d692..d431fc657 100644 --- a/src/app/VerifyConfig.hpp +++ b/src/app/VerifyConfig.hpp @@ -28,7 +28,7 @@ parseConfig(std::string_view configPath) } auto const errors = getClioConfig().parse(json.value()); if (errors.has_value()) { - for (auto const& err : errors.value()) { + for (auto const& err : *errors) { std::cerr << "Issues found in provided config '" << configPath << "':\n"; std::cerr << err.error << std::endl; } diff --git a/src/app/WebHandlers.cpp b/src/app/WebHandlers.cpp index 687395775..9c895891e 100644 --- a/src/app/WebHandlers.cpp +++ b/src/app/WebHandlers.cpp @@ -83,7 +83,7 @@ MetricsHandler::operator()( ASSERT(onTaskComplete.has_value(), "Coroutine group can't be full"); bool const postSuccessful = workQueue_.get().postCoro( - [this, &request, &response, &onTaskComplete = onTaskComplete.value(), &connectionMetadata]( + [this, &request, &response, &onTaskComplete = *onTaskComplete, &connectionMetadata]( // NOLINT(bugprone-unchecked-optional-access) boost::asio::yield_context ) mutable { auto const maybeHttpRequest = request.asHttpRequest(); @@ -94,7 +94,7 @@ MetricsHandler::operator()( httpRequest, adminVerifier_->isAdmin(httpRequest, connectionMetadata.ip()) ); ASSERT(maybeResponse.has_value(), "Got unexpected request for Prometheus"); - response = web::ng::Response{std::move(maybeResponse).value(), request}; + response = web::ng::Response{*std::move(maybeResponse), request}; // notify the coroutine group that the foreign task is done onTaskComplete(); }, @@ -114,7 +114,7 @@ MetricsHandler::operator()( coroutineGroup.asyncWait(yield); ASSERT(response.has_value(), "Woke up coroutine without setting response"); - return std::move(response).value(); + return *std::move(response); // NOLINT(bugprone-unchecked-optional-access) } web::ng::Response diff --git a/src/cluster/ClioNode.cpp b/src/cluster/ClioNode.cpp index 6222a2fec..ab7b762d0 100644 --- a/src/cluster/ClioNode.cpp +++ b/src/cluster/ClioNode.cpp @@ -108,7 +108,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::value const& jv) // Json data doesn't contain uuid so leaving it empty here. It will be filled outside of // this parsing .uuid = std::make_shared(), - .updateTime = updateTime.value(), + .updateTime = *updateTime, .dbRole = dbRole, .etlStarted = etlStarted, .cacheIsFull = cacheIsFull, diff --git a/src/data/AmendmentCenter.hpp b/src/data/AmendmentCenter.hpp index 744c71c5f..d23665cc5 100644 --- a/src/data/AmendmentCenter.hpp +++ b/src/data/AmendmentCenter.hpp @@ -159,6 +159,7 @@ struct Amendments { REGISTER(fix1523); REGISTER(fix1528); REGISTER(fixBatchInnerSigs); + REGISTER(fixCleanup3_1_3); // NOLINTEND(readability-identifier-naming) /** @endcond */ }; diff --git a/src/data/BackendCounters.hpp b/src/data/BackendCounters.hpp index 7d3e93855..1ca5e15b1 100644 --- a/src/data/BackendCounters.hpp +++ b/src/data/BackendCounters.hpp @@ -130,7 +130,7 @@ public: * * @return The report */ - boost::json::object + [[nodiscard]] boost::json::object report() const; private: @@ -152,7 +152,7 @@ private: void registerError(std::uint64_t count); - boost::json::object + [[nodiscard]] boost::json::object report() const; private: diff --git a/src/data/BackendInterface.cpp b/src/data/BackendInterface.cpp index f734012b0..a7cadee6f 100644 --- a/src/data/BackendInterface.cpp +++ b/src/data/BackendInterface.cpp @@ -188,7 +188,7 @@ BackendInterface::fetchBookOffers( auto mid2 = std::chrono::system_clock::now(); numSucc++; succMillis += getMillis(mid2 - mid1); - if (!offerDir || offerDir->key >= bookEnd) { + if (not offerDir.has_value() || offerDir->key >= bookEnd) { LOG(log_.trace()) << "offerDir.has_value() " << offerDir.has_value() << " breaking"; break; } @@ -208,8 +208,10 @@ BackendInterface::fetchBookOffers( auto nextKey = ripple::keylet::page(uTipIndex, next); auto nextDir = fetchLedgerObject(nextKey.key, ledgerSequence, yield); ASSERT(nextDir.has_value(), "Next dir must exist"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) offerDir->blob = *nextDir; offerDir->key = nextKey.key; + // NOLINTEND(bugprone-unchecked-optional-access) } auto mid3 = std::chrono::system_clock::now(); pageMillis += getMillis(mid3 - mid2); @@ -312,6 +314,7 @@ BackendInterface::fetchLedgerPage( return (cursor ? *cursor : kFIRST_KEY); }(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) std::uint32_t const seq = outOfOrder ? range_->maxSequence : ledgerSequence; auto succ = fetchSuccessorKey(curCursor, seq, yield); diff --git a/src/data/BackendInterface.hpp b/src/data/BackendInterface.hpp index fbb5d15f5..d677a2ee3 100644 --- a/src/data/BackendInterface.hpp +++ b/src/data/BackendInterface.hpp @@ -42,7 +42,7 @@ public: /** * @return The error message as a C string */ - char const* + [[nodiscard]] char const* what() const throw() override { return "Database read timed out. Please retry the request"; diff --git a/src/data/CassandraBackend.hpp b/src/data/CassandraBackend.hpp index a5b0bfea7..4c75ea4b0 100644 --- a/src/data/CassandraBackend.hpp +++ b/src/data/CassandraBackend.hpp @@ -99,7 +99,7 @@ public: return true; } - NFTsAndCursor + [[nodiscard]] NFTsAndCursor fetchNFTsByIssuer( ripple::AccountID const& issuer, std::optional const& taxon, @@ -190,7 +190,7 @@ public: return ret; } - std::vector + [[nodiscard]] std::vector fetchAccountRoots( std::uint32_t number, std::uint32_t pageSize, diff --git a/src/data/KeyspaceBackend.hpp b/src/data/KeyspaceBackend.hpp index 76681cbf9..07fe364c6 100644 --- a/src/data/KeyspaceBackend.hpp +++ b/src/data/KeyspaceBackend.hpp @@ -102,7 +102,7 @@ public: return true; } - NFTsAndCursor + [[nodiscard]] NFTsAndCursor fetchNFTsByIssuer( ripple::AccountID const& issuer, std::optional const& taxon, @@ -162,7 +162,7 @@ public: * @param yield The coroutine context. * @return A vector of ripple::uint256 representing the account root hashes. */ - std::vector + [[nodiscard]] std::vector fetchAccountRoots( [[maybe_unused]] std::uint32_t number, [[maybe_unused]] std::uint32_t pageSize, @@ -175,7 +175,7 @@ public: } private: - std::vector + [[nodiscard]] std::vector fetchNFTIDsByTaxon( ripple::AccountID const& issuer, std::uint32_t const taxon, @@ -198,7 +198,7 @@ private: return nftIDs; } - std::vector + [[nodiscard]] std::vector fetchNFTIDsWithoutTaxon( ripple::AccountID const& issuer, std::uint32_t const limit, @@ -242,7 +242,7 @@ private: * @brief Takes a list of NFT IDs, fetches their full data, and assembles the final result with * a cursor. */ - NFTsAndCursor + [[nodiscard]] NFTsAndCursor populateNFTsAndCreateCursor( std::vector const& nftIDs, std::uint32_t const ledgerSequence, diff --git a/src/data/LedgerCacheInterface.hpp b/src/data/LedgerCacheInterface.hpp index 45b542d30..6e9126784 100644 --- a/src/data/LedgerCacheInterface.hpp +++ b/src/data/LedgerCacheInterface.hpp @@ -55,7 +55,7 @@ public: * @param seq The sequence to fetch for * @return If found in cache, will return the cached Blob; otherwise nullopt is returned */ - virtual std::optional + [[nodiscard]] virtual std::optional get(ripple::uint256 const& key, uint32_t seq) const = 0; /** @@ -65,7 +65,7 @@ public: * @param seq The sequence to fetch for * @return If found in deleted cache, will return the cached Blob; otherwise nullopt is returned */ - virtual std::optional + [[nodiscard]] virtual std::optional getDeleted(ripple::uint256 const& key, uint32_t seq) const = 0; /** @@ -77,7 +77,7 @@ public: * @param seq The sequence to fetch for * @return If found in cache, will return the cached successor; otherwise nullopt is returned */ - virtual std::optional + [[nodiscard]] virtual std::optional getSuccessor(ripple::uint256 const& key, uint32_t seq) const = 0; /** @@ -89,7 +89,7 @@ public: * @param seq The sequence to fetch for * @return If found in cache, will return the cached predcessor; otherwise nullopt is returned */ - virtual std::optional + [[nodiscard]] virtual std::optional getPredecessor(ripple::uint256 const& key, uint32_t seq) const = 0; /** @@ -101,7 +101,7 @@ public: /** * @return true if the cache is disabled; false otherwise */ - virtual bool + [[nodiscard]] virtual bool isDisabled() const = 0; /** @@ -117,33 +117,33 @@ public: /** * @return The latest ledger sequence for which cache is available. */ - virtual uint32_t + [[nodiscard]] virtual uint32_t latestLedgerSequence() const = 0; /** * @return true if the cache has all data for the most recent ledger; false otherwise */ - virtual bool + [[nodiscard]] virtual bool isFull() const = 0; /** * @return The total size of the cache. */ - virtual size_t + [[nodiscard]] virtual size_t size() const = 0; /** * @return A number representing the success rate of hitting an object in the cache versus * missing it. */ - virtual float + [[nodiscard]] virtual float getObjectHitRate() const = 0; /** * @return A number representing the success rate of hitting a successor in the cache versus * missing it. */ - virtual float + [[nodiscard]] virtual float getSuccessorHitRate() const = 0; /** diff --git a/src/data/cassandra/CassandraBackendFamily.hpp b/src/data/cassandra/CassandraBackendFamily.hpp index 1583548d2..50166ac48 100644 --- a/src/data/cassandra/CassandraBackendFamily.hpp +++ b/src/data/cassandra/CassandraBackendFamily.hpp @@ -564,7 +564,7 @@ public: << ", key = " << ripple::to_string(key); if (auto const res = executor_.read(yield, schema_->selectObject, key, sequence); res) { if (auto const result = res->template get(); result) { - auto [_, seq] = result.value(); + auto [_, seq] = *result; return seq; } LOG(log_.debug()) << "Could not fetch ledger object sequence - no rows"; @@ -923,14 +923,15 @@ public: record.tokenID )); statements.push_back(schema_->insertNFTURI.bind( - record.tokenID, record.ledgerSequence, record.uri.value() + record.tokenID, record.ledgerSequence, *record.uri )); } } else { // only uri changed, we update the uri table only - statements.push_back(schema_->insertNFTURI.bind( - record.tokenID, record.ledgerSequence, record.uri.value() - )); + statements.push_back( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + schema_->insertNFTURI.bind(record.tokenID, record.ledgerSequence, *record.uri) + ); } } @@ -1002,7 +1003,7 @@ protected: return false; } - if (not maybeSuccess.value()) { + if (not *maybeSuccess) { LOG(log_.warn()) << "Update failed. Checking if DB state is what we expect"; // error may indicate that another writer wrote something. diff --git a/src/data/cassandra/Error.hpp b/src/data/cassandra/Error.hpp index 25bf0f8eb..88709ef47 100644 --- a/src/data/cassandra/Error.hpp +++ b/src/data/cassandra/Error.hpp @@ -65,7 +65,7 @@ public: /** * @return The final error message as a std::string */ - std::string + [[nodiscard]] std::string message() const { return message_; @@ -74,7 +74,7 @@ public: /** * @return The error code */ - uint32_t + [[nodiscard]] uint32_t code() const { return code_; @@ -83,7 +83,7 @@ public: /** * @return true if the wrapped error is considered a timeout; false otherwise */ - bool + [[nodiscard]] bool isTimeout() const { return code_ == CASS_ERROR_LIB_NO_HOSTS_AVAILABLE or @@ -94,7 +94,7 @@ public: /** * @return true if the wrapped error is an invalid query; false otherwise */ - bool + [[nodiscard]] bool isInvalidQuery() const { return code_ == CASS_ERROR_SERVER_INVALID_QUERY; diff --git a/src/data/cassandra/Handle.hpp b/src/data/cassandra/Handle.hpp index 9b4e3e7eb..9376deb31 100644 --- a/src/data/cassandra/Handle.hpp +++ b/src/data/cassandra/Handle.hpp @@ -114,7 +114,7 @@ public: * * @return Possibly an error */ - [[maybe_unused]] MaybeErrorType + [[nodiscard]] [[maybe_unused]] MaybeErrorType disconnect() const; /** @@ -162,7 +162,7 @@ public: * @return The result or an error */ template - [[maybe_unused]] ResultOrErrorType + [[nodiscard]] [[maybe_unused]] ResultOrErrorType execute(std::string_view query, Args&&... args) const { return asyncExecute(query, std::forward(args)...).get(); @@ -189,7 +189,7 @@ public: * @param statements The statements to execute * @return Possibly an error */ - [[maybe_unused]] MaybeErrorType + [[nodiscard]] [[maybe_unused]] MaybeErrorType executeEach(std::vector const& statements) const; /** @@ -250,7 +250,7 @@ public: * @param statement The statement to execute * @return The result or an error */ - [[maybe_unused]] ResultOrErrorType + [[nodiscard]] [[maybe_unused]] ResultOrErrorType execute(StatementType const& statement) const; /** @@ -270,7 +270,7 @@ public: * @param statements The statements to execute * @return Possibly an error */ - [[maybe_unused]] MaybeErrorType + [[nodiscard]] [[maybe_unused]] MaybeErrorType execute(std::vector const& statements) const; /** diff --git a/src/data/cassandra/impl/Cluster.cpp b/src/data/cassandra/impl/Cluster.cpp index 9b1b14c5f..c75c42d3a 100644 --- a/src/data/cassandra/impl/Cluster.cpp +++ b/src/data/cassandra/impl/Cluster.cpp @@ -123,8 +123,8 @@ Cluster::setupContactPoints(Settings::ContactPoints const& points) } if (points.port) { - auto const rc = cass_cluster_set_port(*this, points.port.value()); - throwErrorIfNeeded(rc, "port", to_string(points.port.value())); + auto const rc = cass_cluster_set_port(*this, *points.port); + throwErrorIfNeeded(rc, "port", to_string(*points.port)); } } @@ -158,10 +158,8 @@ Cluster::setupCredentials(Settings const& settings) if (not settings.username || not settings.password) return; - LOG(log_.debug()) << "Set credentials; username: " << settings.username.value(); - cass_cluster_set_credentials( - *this, settings.username.value().c_str(), settings.password.value().c_str() - ); + LOG(log_.debug()) << "Set credentials; username: " << *settings.username; + cass_cluster_set_credentials(*this, settings.username->c_str(), settings.password->c_str()); } } // namespace data::cassandra::impl diff --git a/src/data/cassandra/impl/ExecutionStrategy.hpp b/src/data/cassandra/impl/ExecutionStrategy.hpp index 805de0e55..fb874c277 100644 --- a/src/data/cassandra/impl/ExecutionStrategy.hpp +++ b/src/data/cassandra/impl/ExecutionStrategy.hpp @@ -525,13 +525,13 @@ private: { // mutex lock required to prevent race condition around spurious // wakeup - std::lock_guard const lck(throttleMutex_); + std::scoped_lock const lck(throttleMutex_); throttleCv_.notify_one(); } if (cur == 0) { // mutex lock required to prevent race condition around spurious // wakeup - std::lock_guard const lck(syncMutex_); + std::scoped_lock const lck(syncMutex_); syncCv_.notify_one(); } } diff --git a/src/data/cassandra/impl/Future.hpp b/src/data/cassandra/impl/Future.hpp index b906aac7b..4dbe1a5aa 100644 --- a/src/data/cassandra/impl/Future.hpp +++ b/src/data/cassandra/impl/Future.hpp @@ -13,10 +13,10 @@ namespace data::cassandra::impl { struct Future : public ManagedObject { /* implicit */ Future(CassFuture* ptr); - MaybeError + [[nodiscard]] MaybeError await() const; - ResultOrError + [[nodiscard]] ResultOrError get() const; }; diff --git a/src/data/cassandra/impl/Result.hpp b/src/data/cassandra/impl/Result.hpp index 5c177d6ab..4e422bc3d 100644 --- a/src/data/cassandra/impl/Result.hpp +++ b/src/data/cassandra/impl/Result.hpp @@ -108,7 +108,7 @@ struct Result : public ManagedObject { hasRows() const; template - std::optional> + [[nodiscard]] std::optional> get() const requires(std::tuple_size>{} > 1) { @@ -126,7 +126,7 @@ struct Result : public ManagedObject { } template - std::optional + [[nodiscard]] std::optional get() const { // row managed internally by cassandra driver, hence no ManagedObject. @@ -153,7 +153,7 @@ public: hasMore() const; template - std::tuple + [[nodiscard]] std::tuple extractCurrentRow() const { // note: row is invalidated on each iteration. diff --git a/src/data/cassandra/impl/Statement.hpp b/src/data/cassandra/impl/Statement.hpp index 481614354..d70aeb65c 100644 --- a/src/data/cassandra/impl/Statement.hpp +++ b/src/data/cassandra/impl/Statement.hpp @@ -171,7 +171,7 @@ public: * @return A bound and ready to execute Statement object */ template - Statement + [[nodiscard]] Statement bind(Args&&... args) const { Statement statement = cass_prepared_bind(*this); diff --git a/src/data/cassandra/impl/Tuple.hpp b/src/data/cassandra/impl/Tuple.hpp index 98928d21e..8f04ababa 100644 --- a/src/data/cassandra/impl/Tuple.hpp +++ b/src/data/cassandra/impl/Tuple.hpp @@ -93,7 +93,7 @@ public: private: template - Type + [[nodiscard]] Type extractNext() const { using std::to_string; diff --git a/src/etl/CacheLoaderSettings.cpp b/src/etl/CacheLoaderSettings.cpp index e71009093..ba380aeb6 100644 --- a/src/etl/CacheLoaderSettings.cpp +++ b/src/etl/CacheLoaderSettings.cpp @@ -47,8 +47,7 @@ makeCacheLoaderSettings(util::config::ClioConfigDefinition const& config) if (auto filePath = cache.maybeValue("file.path"); filePath.has_value()) { settings.cacheFileSettings = CacheLoaderSettings::CacheFileSettings{ - .path = std::move(filePath).value(), - .maxAge = cache.get("file.max_sequence_age") + .path = *std::move(filePath), .maxAge = cache.get("file.max_sequence_age") }; } diff --git a/src/etl/ETLService.cpp b/src/etl/ETLService.cpp index be7bfc93a..721c4fe33 100644 --- a/src/etl/ETLService.cpp +++ b/src/etl/ETLService.cpp @@ -417,6 +417,7 @@ ETLService::attemptTakeoverWriter() auto rng = backend_->hardFetchLedgerRangeNoThrow(); ASSERT(rng.has_value(), "Ledger range can't be null"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) if (backend_->cache().latestLedgerSequence() != rng->maxSequence) { LOG(log_.info()) << "Wanted to take over the ETL writer seat but LedgerCache is outdated"; // Give ETL time to update LedgerCache. This method will be called because @@ -426,7 +427,7 @@ ETLService::attemptTakeoverWriter() state_->isWriting = true; // switch to writer LOG(log_.info()) << "Taking over the ETL writer seat"; - startLoading(rng->maxSequence + 1); + startLoading(rng->maxSequence + 1); // NOLINT(bugprone-unchecked-optional-access) } void diff --git a/src/etl/LedgerPublisherInterface.hpp b/src/etl/LedgerPublisherInterface.hpp index 656bbb53b..6eab66d10 100644 --- a/src/etl/LedgerPublisherInterface.hpp +++ b/src/etl/LedgerPublisherInterface.hpp @@ -32,7 +32,7 @@ struct LedgerPublisherInterface { * * @return A std::chrono::time_point representing the time of the last publish */ - virtual std::chrono::time_point + [[nodiscard]] virtual std::chrono::time_point getLastPublish() const = 0; /** @@ -40,7 +40,7 @@ struct LedgerPublisherInterface { * * @return The number of seconds since the last ledger close as std::uint32_t */ - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t lastCloseAgeSeconds() const = 0; /** @@ -48,7 +48,7 @@ struct LedgerPublisherInterface { * * @return The number of seconds since the last publish as std::uint32_t */ - virtual std::uint32_t + [[nodiscard]] virtual std::uint32_t lastPublishAgeSeconds() const = 0; }; diff --git a/src/etl/LoadBalancer.cpp b/src/etl/LoadBalancer.cpp index 3178c4281..50f8fb14e 100644 --- a/src/etl/LoadBalancer.cpp +++ b/src/etl/LoadBalancer.cpp @@ -275,10 +275,11 @@ LoadBalancer::forwardToRippled( return std::unexpected{rpc::ClioError::RpcCommandIsMissing}; auto const cmd = boost::json::value_to(request.at("command")); - if (forwardingCache_) { + if (shouldUseCache(isAdmin)) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) if (auto cachedResponse = forwardingCache_->get(cmd); cachedResponse) { forwardingCounters_.cacheHit.get() += 1; - return std::move(cachedResponse).value(); + return *std::move(cachedResponse); } } forwardingCounters_.cacheMiss.get() += 1; @@ -310,9 +311,9 @@ LoadBalancer::forwardToRippled( } if (response) { - if (forwardingCache_ and not response->contains("error")) - forwardingCache_->put(cmd, *response); - return std::move(response).value(); + if (shouldUseCache(isAdmin) and not response->contains("error")) + forwardingCache_->put(cmd, *response); // NOLINT(bugprone-unchecked-optional-access) + return *std::move(response); } return std::unexpected{error}; @@ -415,4 +416,10 @@ LoadBalancer::chooseForwardingSource() } } +bool +LoadBalancer::shouldUseCache(bool isAdmin) const +{ + return forwardingCache_.has_value() and not isAdmin; +} + } // namespace etl diff --git a/src/etl/LoadBalancer.hpp b/src/etl/LoadBalancer.hpp index 58baa4bd6..30896f68e 100644 --- a/src/etl/LoadBalancer.hpp +++ b/src/etl/LoadBalancer.hpp @@ -254,6 +254,9 @@ private: */ void chooseForwardingSource(); + + bool + shouldUseCache(bool isAdmin) const; }; } // namespace etl diff --git a/src/etl/NetworkValidatedLedgers.cpp b/src/etl/NetworkValidatedLedgers.cpp index ef1656eb0..a1539be38 100644 --- a/src/etl/NetworkValidatedLedgers.cpp +++ b/src/etl/NetworkValidatedLedgers.cpp @@ -18,7 +18,7 @@ NetworkValidatedLedgers::makeValidatedLedgers() void NetworkValidatedLedgers::push(uint32_t idx) { - std::lock_guard const lck(mtx_); + std::scoped_lock const lck(mtx_); if (!latest_ || idx > *latest_) latest_ = idx; diff --git a/src/etl/WriterState.hpp b/src/etl/WriterState.hpp index 79049c3c5..0cb8f083e 100644 --- a/src/etl/WriterState.hpp +++ b/src/etl/WriterState.hpp @@ -171,14 +171,14 @@ public: */ WriterState(std::shared_ptr state, data::LedgerCacheInterface const& cache); - bool + [[nodiscard]] bool isReadOnly() const override; /** * @brief Check if the ETL process is currently writing to the database. * @return true if the process is writing, false otherwise */ - bool + [[nodiscard]] bool isWriting() const override; /** @@ -213,11 +213,11 @@ public: * * @return true if the cluster has switched to fallback mode, false otherwise */ - bool + [[nodiscard]] bool isFallback() const override; /** @copydoc WriterStateInterface::isFallbackRecovery */ - bool + [[nodiscard]] bool isFallbackRecovery() const override; /** @copydoc WriterStateInterface::setFallbackRecovery */ @@ -225,11 +225,11 @@ public: setFallbackRecovery(bool newValue) override; /** @copydoc WriterStateInterface::isEtlStarted */ - bool + [[nodiscard]] bool isEtlStarted() const override; /** @copydoc WriterStateInterface::isCacheFull */ - bool + [[nodiscard]] bool isCacheFull() const override; /** @@ -239,7 +239,7 @@ public: * * @return A unique pointer to the cloned writer state. */ - std::unique_ptr + [[nodiscard]] std::unique_ptr clone() const override; }; diff --git a/src/etl/impl/CacheLoader.hpp b/src/etl/impl/CacheLoader.hpp index dadb234ef..2641cdf0a 100644 --- a/src/etl/impl/CacheLoader.hpp +++ b/src/etl/impl/CacheLoader.hpp @@ -104,7 +104,7 @@ private: return; // queue is empty } - auto [start, end] = cursor.value(); + auto [start, end] = *cursor; LOG(log_.debug()) << "Starting a cursor: " << ripple::strHex(start); while (not token.isStopRequested() and not cache_.get().isDisabled()) { @@ -136,7 +136,7 @@ private: break; // pick up the next cursor if available } - start = std::move(res.cursor).value(); + start = *std::move(res.cursor); } } }); diff --git a/src/etl/impl/CursorFromDiffProvider.hpp b/src/etl/impl/CursorFromDiffProvider.hpp index 5de0e098a..538809a09 100644 --- a/src/etl/impl/CursorFromDiffProvider.hpp +++ b/src/etl/impl/CursorFromDiffProvider.hpp @@ -46,6 +46,7 @@ public: std::set liveCursors; std::set deletedCursors; auto i = 0; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) while (liveCursors.size() < numCursors_ and seq - i >= range->minSequence) { auto diffs = fetchDiff(i++); rg::copy( diff --git a/src/etl/impl/Extraction.cpp b/src/etl/impl/Extraction.cpp index 929d51059..93256a22a 100644 --- a/src/etl/impl/Extraction.cpp +++ b/src/etl/impl/Extraction.cpp @@ -94,6 +94,8 @@ extractObj(PBObjType obj) { auto const key = ripple::uint256::fromVoidChecked(obj.key()); ASSERT(key.has_value(), "Failed to deserialize key from void"); + if (!key) + return {}; auto const valueOr = [](std::string const& maybe, std::string fallback) -> std::string { if (maybe.empty()) diff --git a/src/etl/impl/ForwardingSource.hpp b/src/etl/impl/ForwardingSource.hpp index 29360e41d..05d2dee80 100644 --- a/src/etl/impl/ForwardingSource.hpp +++ b/src/etl/impl/ForwardingSource.hpp @@ -39,7 +39,7 @@ public: * @param yield The coroutine context * @return Response on success or error on failure */ - std::expected + [[nodiscard]] std::expected forwardToRippled( boost::json::object const& request, std::optional const& forwardToRippledClientIp, diff --git a/src/etl/impl/LedgerPublisher.hpp b/src/etl/impl/LedgerPublisher.hpp index a750358ae..1fac36f4d 100644 --- a/src/etl/impl/LedgerPublisher.hpp +++ b/src/etl/impl/LedgerPublisher.hpp @@ -139,6 +139,8 @@ public: "Ledger must exist in database. Ledger sequence = {}", ledgerSequence ); + if (!lgr) + return false; publish(*lgr); return true; diff --git a/src/etl/impl/Monitor.cpp b/src/etl/impl/Monitor.cpp index ebb781ac8..b89c3650e 100644 --- a/src/etl/impl/Monitor.cpp +++ b/src/etl/impl/Monitor.cpp @@ -51,6 +51,8 @@ Monitor::notifySequenceLoaded(uint32_t seq) lck->lastSeenMaxSeqInDb = std::max(seq, lck->lastSeenMaxSeqInDb); lck->lastDbCheckTime = std::chrono::steady_clock::now(); } + + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) repeatedTask_->invoke(); // force-invoke doWork immediately }; @@ -110,6 +112,8 @@ Monitor::onNextSequence(uint32_t seq) { ASSERT(repeatedTask_.has_value(), "Ledger subscription without repeated task is a logic error"); LOG(log_.debug()) << "Notified about new sequence on the network: " << seq; + + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) repeatedTask_->invoke(); // force-invoke immediately } diff --git a/src/etl/impl/SourceImpl.hpp b/src/etl/impl/SourceImpl.hpp index 102c2ef92..371e3784e 100644 --- a/src/etl/impl/SourceImpl.hpp +++ b/src/etl/impl/SourceImpl.hpp @@ -97,7 +97,7 @@ public: * * @return true if source is connected; false otherwise */ - bool + [[nodiscard]] bool isConnected() const final { return subscriptionSource_->isConnected(); @@ -119,7 +119,7 @@ public: * * @return JSON representation of the source */ - boost::json::object + [[nodiscard]] boost::json::object toJson() const final { boost::json::object res; @@ -144,7 +144,7 @@ public: } /** @return String representation of the source (for debug) */ - std::string + [[nodiscard]] std::string toString() const final { return "{validated range: " + subscriptionSource_->validatedRange() + ", ip: " + ip_ + @@ -157,7 +157,7 @@ public: * @param sequence The ledger sequence to check * @return true if ledger is in the range of this source; false otherwise */ - bool + [[nodiscard]] bool hasLedger(uint32_t sequence) const final { return subscriptionSource_->hasLedger(sequence); @@ -208,7 +208,7 @@ public: * @param yield The coroutine context * @return Response or ClioError */ - std::expected + [[nodiscard]] std::expected forwardToRippled( boost::json::object const& request, std::optional const& forwardToRippledClientIp, diff --git a/src/etl/impl/SubscriptionSource.cpp b/src/etl/impl/SubscriptionSource.cpp index e406a2391..d8618df9c 100644 --- a/src/etl/impl/SubscriptionSource.cpp +++ b/src/etl/impl/SubscriptionSource.cpp @@ -155,7 +155,7 @@ SubscriptionSource::subscribe() if (auto const writeErrorOpt = wsConnection_->write(subscribeCommand, yield, wsTimeout_); writeErrorOpt) { - handleError(writeErrorOpt.value(), yield); + handleError(*writeErrorOpt, yield); return; } @@ -172,8 +172,8 @@ SubscriptionSource::subscribe() return; } - if (auto const handleErrorOpt = handleMessage(message.value()); handleErrorOpt) { - handleError(handleErrorOpt.value(), yield); + if (auto const handleErrorOpt = handleMessage(*message); handleErrorOpt) { + handleError(*handleErrorOpt, yield); return; } } @@ -296,8 +296,8 @@ SubscriptionSource::logError(util::requests::RequestError const& error) const auto const& errorCodeOpt = error.errorCode(); if (not errorCodeOpt or - (errorCodeOpt.value() != boost::asio::error::operation_aborted && - errorCodeOpt.value() != boost::asio::error::connection_refused)) { + (*errorCodeOpt != boost::asio::error::operation_aborted && + *errorCodeOpt != boost::asio::error::connection_refused)) { LOG(log_.error()) << error.message(); } else { LOG(log_.warn()) << error.message(); diff --git a/src/etl/impl/ext/Successor.cpp b/src/etl/impl/ext/Successor.cpp index 880bf1838..5bb012141 100644 --- a/src/etl/impl/ext/Successor.cpp +++ b/src/etl/impl/ext/Successor.cpp @@ -37,7 +37,7 @@ SuccessorExt::onInitialData(model::LedgerData const& data) const ASSERT(data.edgeKeys.has_value(), "Expecting to have edge keys on initial data load"); ASSERT(data.objects.empty(), "Should not have objects from initial data"); writeSuccessors(data.seq); - writeEdgeKeys(data.seq, data.edgeKeys.value()); + writeEdgeKeys(data.seq, *data.edgeKeys); // NOLINT(bugprone-unchecked-optional-access) } void @@ -67,7 +67,7 @@ SuccessorExt::onLedgerData(model::LedgerData const& data) const | vs::filter([](auto const& obj) { return obj.type != model::Object::ModType::Modified; }); if (data.successors.has_value()) { - for (auto const& successor : data.successors.value()) + for (auto const& successor : *data.successors) writeIncludedSuccessor(data.seq, successor); for (auto const& obj : filteredObjects) @@ -135,7 +135,7 @@ SuccessorExt::updateSuccessorFromCache(uint32_t seq, model::Object const& obj) c auto const old = cache_.get().getDeleted(obj.key, seq - 1); ASSERT(old.has_value(), "Deleted object {} must be in cache", ripple::strHex(obj.key)); - checkBookBase = isBookDir(obj.key, *old); + checkBookBase = isBookDir(obj.key, *old); // NOLINT(bugprone-unchecked-optional-access) } else { checkBookBase = isBookDir(obj.key, obj.data); } @@ -191,7 +191,7 @@ SuccessorExt::writeSuccessors(uint32_t seq) const succ.has_value(), "Book base {} must have a successor", ripple::strHex(base) ); - if (succ->key == cur->key) + if (succ->key == cur->key) // NOLINT(bugprone-unchecked-optional-access) backend_->writeSuccessor(uint256ToString(base), seq, uint256ToString(cur->key)); } } @@ -206,6 +206,7 @@ void SuccessorExt::writeEdgeKeys(std::uint32_t seq, auto const& edgeKeys) const { for (auto const& key : edgeKeys) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto succ = cache_.get().getSuccessor(*ripple::uint256::fromVoidChecked(key), seq); if (succ) backend_->writeSuccessor(auto{key}, seq, uint256ToString(succ->key)); diff --git a/src/feed/SubscriptionManagerInterface.hpp b/src/feed/SubscriptionManagerInterface.hpp index 85d8e0de4..2d07586e2 100644 --- a/src/feed/SubscriptionManagerInterface.hpp +++ b/src/feed/SubscriptionManagerInterface.hpp @@ -236,7 +236,7 @@ public: * * @return The report of the number of subscribers. */ - virtual boost::json::object + [[nodiscard]] virtual boost::json::object report() const = 0; /** @@ -251,7 +251,7 @@ public: * * @return The network id. */ - virtual uint32_t + [[nodiscard]] virtual uint32_t getNetworkID() const = 0; }; diff --git a/src/feed/impl/LedgerFeed.cpp b/src/feed/impl/LedgerFeed.cpp index 810c4c853..3454f66b4 100644 --- a/src/feed/impl/LedgerFeed.cpp +++ b/src/feed/impl/LedgerFeed.cpp @@ -57,16 +57,21 @@ LedgerFeed::sub( auto const ledgerRange = backend->fetchLedgerRange(); ASSERT(ledgerRange.has_value(), "Ledger range must be valid"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const lgrInfo = backend->fetchLedgerBySequence(ledgerRange->maxSequence, yield); ASSERT(lgrInfo.has_value(), "Ledger must be valid"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const fees = backend->fetchFees(lgrInfo->seq, yield); ASSERT(fees.has_value(), "Fees must be valid"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) auto const range = std::to_string(ledgerRange->minSequence) + "-" + std::to_string(ledgerRange->maxSequence); auto pubMsg = makeLedgerPubMessage(*lgrInfo, *fees, range, 0, networkID); + // NOLINTEND(bugprone-unchecked-optional-access) + pubMsg.erase("txn_count"); pubMsg.erase("type"); diff --git a/src/feed/impl/TrackableSignal.hpp b/src/feed/impl/TrackableSignal.hpp index 7f933deff..1906420aa 100644 --- a/src/feed/impl/TrackableSignal.hpp +++ b/src/feed/impl/TrackableSignal.hpp @@ -106,7 +106,7 @@ public: /** * @brief Get the number of connections. */ - std::size_t + [[nodiscard]] std::size_t count() const { return connections_.template lock()->size(); diff --git a/src/feed/impl/TransactionFeed.cpp b/src/feed/impl/TransactionFeed.cpp index 5b48f15a9..563450d9a 100644 --- a/src/feed/impl/TransactionFeed.cpp +++ b/src/feed/impl/TransactionFeed.cpp @@ -234,7 +234,7 @@ TransactionFeed::pub( networkID ); ctid) - pubObj[JS(ctid)] = ctid.value(); + pubObj[JS(ctid)] = *ctid; } pubObj[JS(type)] = "transaction"; diff --git a/src/migration/MigrationApplication.cpp b/src/migration/MigrationApplication.cpp index 076c6ca5e..e942690d1 100644 --- a/src/migration/MigrationApplication.cpp +++ b/src/migration/MigrationApplication.cpp @@ -72,13 +72,13 @@ int MigratorApplication::migrate(std::string const& migratorName) { auto const status = migrationManager_->getMigratorStatusByName(migratorName); - if (status == migration::MigratorStatus::Migrated) { + if (status == migration::MigratorStatus::Status::Migrated) { std::cout << "Migrator " << migratorName << " has already migrated" << std::endl; printStatus(); return EXIT_SUCCESS; } - if (status == migration::MigratorStatus::NotKnown) { + if (status == migration::MigratorStatus::Status::NotKnown) { std::cout << "Migrator " << migratorName << " not found" << std::endl; printStatus(); return EXIT_FAILURE; diff --git a/src/migration/MigrationInspectorFactory.hpp b/src/migration/MigrationInspectorFactory.hpp index fea38be46..529b0e6ad 100644 --- a/src/migration/MigrationInspectorFactory.hpp +++ b/src/migration/MigrationInspectorFactory.hpp @@ -36,7 +36,7 @@ makeMigrationInspector( // Database is empty, we need to initialize the migration table if it is a writeable backend if (not config.get("read_only") and not backend->hardFetchLedgerRangeNoThrow()) { - migration::MigratorStatus const migrated(migration::MigratorStatus::Migrated); + migration::MigratorStatus const migrated(migration::MigratorStatus::Status::Migrated); for (auto const& name : inspector->allMigratorsNames()) { backend->writeMigratorStatus(name, migrated.toString()); } diff --git a/src/migration/MigrationInspectorInterface.hpp b/src/migration/MigrationInspectorInterface.hpp index 1d33c8e6d..5bb8bba3a 100644 --- a/src/migration/MigrationInspectorInterface.hpp +++ b/src/migration/MigrationInspectorInterface.hpp @@ -20,7 +20,7 @@ struct MigrationInspectorInterface { * @return A vector of tuple, the first element is the migrator's name, the second element is * the status of the */ - virtual std::vector> + [[nodiscard]] virtual std::vector> allMigratorsStatusPairs() const = 0; /** @@ -28,7 +28,7 @@ struct MigrationInspectorInterface { * * @return A vector of migrators' names */ - virtual std::vector + [[nodiscard]] virtual std::vector allMigratorsNames() const = 0; /** @@ -37,7 +37,7 @@ struct MigrationInspectorInterface { * @param name The migrator's name * @return The status of the migrator */ - virtual MigratorStatus + [[nodiscard]] virtual MigratorStatus getMigratorStatusByName(std::string const& name) const = 0; /** @@ -46,7 +46,7 @@ struct MigrationInspectorInterface { * @param name The migrator's name * @return The description of the migrator */ - virtual std::string + [[nodiscard]] virtual std::string getMigratorDescriptionByName(std::string const& name) const = 0; /** @@ -54,7 +54,7 @@ struct MigrationInspectorInterface { * * @return True if Clio server is blocked by migration, false otherwise */ - virtual bool + [[nodiscard]] virtual bool isBlockingClio() const = 0; }; diff --git a/src/migration/MigratiorStatus.hpp b/src/migration/MigratiorStatus.hpp index 8b61209ce..b36c8d079 100644 --- a/src/migration/MigratiorStatus.hpp +++ b/src/migration/MigratiorStatus.hpp @@ -15,7 +15,7 @@ public: /** * @brief The status of a migrator */ - enum Status { Migrated, NotMigrated, NotKnown, NumStatuses }; + enum class Status { Migrated, NotMigrated, NotKnown, NumStatuses }; /** * @brief Construct a new Migrator Status object with the given status @@ -48,7 +48,7 @@ public: * * @return The string representation of the status */ - std::string + [[nodiscard]] std::string toString() const; /** @@ -61,11 +61,8 @@ public: fromString(std::string const& statusStr); private: - static constexpr std::array(NumStatuses)> kSTATUS_STR_MAP = { - "Migrated", - "NotMigrated", - "NotKnown" - }; + static constexpr std::array(Status::NumStatuses)> + kSTATUS_STR_MAP = {"Migrated", "NotMigrated", "NotKnown"}; Status status_; }; diff --git a/src/migration/cassandra/impl/Spec.hpp b/src/migration/cassandra/impl/Spec.hpp index 819115042..9daa12bc9 100644 --- a/src/migration/cassandra/impl/Spec.hpp +++ b/src/migration/cassandra/impl/Spec.hpp @@ -13,7 +13,7 @@ concept TableSpec = requires { // Check that 'row' exists and is a tuple // keys types are at the beginning and the other fields types sort in alphabetical order typename T::Row; - requires std::tuple_size::value >= 0; // Ensures 'row' is a tuple + requires std::tuple_size_v >= 0; // Ensures 'row' is a tuple // Check that static constexpr members 'partitionKey' and 'tableName' exist { T::kPARTITION_KEY } -> std::convertible_to; diff --git a/src/migration/impl/MigrationInspectorBase.hpp b/src/migration/impl/MigrationInspectorBase.hpp index 0ceb69ebb..b99deed0f 100644 --- a/src/migration/impl/MigrationInspectorBase.hpp +++ b/src/migration/impl/MigrationInspectorBase.hpp @@ -41,7 +41,7 @@ public: * @return A vector of tuple, the first element is the migrator's name, the second element is * the status of the migrator */ - std::vector> + [[nodiscard]] std::vector> allMigratorsStatusPairs() const override { return migrators_.getMigratorsStatus(); @@ -53,7 +53,7 @@ public: * @param name The name of the migrator * @return The status of the migrator */ - MigratorStatus + [[nodiscard]] MigratorStatus getMigratorStatusByName(std::string const& name) const override { return migrators_.getMigratorStatus(name); @@ -64,7 +64,7 @@ public: * * @return A vector of string, the names of all the migrators */ - std::vector + [[nodiscard]] std::vector allMigratorsNames() const override { auto const names = migrators_.getMigratorNames(); @@ -77,7 +77,7 @@ public: * @param name The name of the migrator * @return The description of the migrator */ - std::string + [[nodiscard]] std::string getMigratorDescriptionByName(std::string const& name) const override { return migrators_.getMigratorDescription(name); @@ -88,7 +88,7 @@ public: * * @return True if server is blocked, false otherwise */ - bool + [[nodiscard]] bool isBlockingClio() const override { return std::ranges::any_of(migrators_.getMigratorNames(), [&](auto const& migrator) { diff --git a/src/migration/impl/MigratorsRegister.hpp b/src/migration/impl/MigratorsRegister.hpp index 08309360a..4f02910dc 100644 --- a/src/migration/impl/MigratorsRegister.hpp +++ b/src/migration/impl/MigratorsRegister.hpp @@ -61,7 +61,7 @@ class MigratorsRegister { LOG(log_.info()) << "Running migration: " << name; Migrator::runMigration(backend_, config); backend_->writeMigratorStatus( - name, MigratorStatus(MigratorStatus::Migrated).toString() + name, MigratorStatus(MigratorStatus::Status::Migrated).toString() ); LOG(log_.info()) << "Finished migration: " << name; } @@ -125,7 +125,7 @@ public: * @return A vector of tuple, the first element is the migrator's name, the second element is * the status of the migrator */ - std::vector> + [[nodiscard]] std::vector> getMigratorsStatus() const { auto const fullList = getMigratorNames(); @@ -145,19 +145,19 @@ public: * @param name The migrator's name to get the status * @return The status of the migrator */ - MigratorStatus + [[nodiscard]] MigratorStatus getMigratorStatus(std::string const& name) const { auto const fullList = getMigratorNames(); if (std::ranges::find(fullList, name) == fullList.end()) { - return MigratorStatus::NotKnown; + return MigratorStatus::Status::NotKnown; } auto const statusStringOpt = data::synchronous([&](auto yield) { return backend_->fetchMigratorStatus(name, yield); }); return statusStringOpt ? MigratorStatus::fromString(statusStringOpt.value()) - : MigratorStatus::NotMigrated; + : MigratorStatus::Status::NotMigrated; } /** @@ -165,7 +165,7 @@ public: * * @return A array of migrator's names */ - constexpr auto + [[nodiscard]] constexpr auto getMigratorNames() const { return std::array{MigratorType::kNAME...}; @@ -177,7 +177,7 @@ public: * @param name The migrator's name * @return The description of the migrator */ - std::string + [[nodiscard]] std::string getMigratorDescription(std::string const& name) const { if constexpr (sizeof...(MigratorType) == 0) { @@ -199,7 +199,7 @@ public: * @return std::nullopt if the migrator name is not found, or a boolean value indicating whether * the migrator is blocking Clio server. */ - std::optional + [[nodiscard]] std::optional canMigratorBlockClio(std::string_view name) const { if constexpr (sizeof...(MigratorType) == 0) { diff --git a/src/rpc/CredentialHelpers.cpp b/src/rpc/CredentialHelpers.cpp index a112bfe4d..ca1cce187 100644 --- a/src/rpc/CredentialHelpers.cpp +++ b/src/rpc/CredentialHelpers.cpp @@ -85,8 +85,12 @@ parseAuthorizeCredentials(boost::json::array const& jv) ); auto credential = ripple::STObject::makeInnerObject(ripple::sfCredential); + + // NOLINTBEGIN(bugprone-unchecked-optional-access) credential.setAccountID(ripple::sfIssuer, *issuer); credential.setFieldVL(ripple::sfCredentialType, *credentialType); + // NOLINTEND(bugprone-unchecked-optional-access) + arr.push_back(std::move(credential)); } @@ -104,7 +108,7 @@ fetchCredentialArray( { ripple::STArray authCreds; std::unordered_set elems; - for (auto const& elem : credID.value()) { + for (auto const& elem : *credID) { // NOLINT(bugprone-unchecked-optional-access) ASSERT( elem.is_string(), "should already be checked in validators.hpp that elem is a string." ); diff --git a/src/rpc/Errors.cpp b/src/rpc/Errors.cpp index bf4d888c4..393d77aae 100644 --- a/src/rpc/Errors.cpp +++ b/src/rpc/Errors.cpp @@ -61,14 +61,14 @@ WarningInfo const& getWarningInfo(WarningCode code) { static constexpr WarningInfo kINFOS[]{ - {WarnUnknown, "Unknown warning"}, - {WarnRpcClio, + {WarningCode::WarnUnknown, "Unknown warning"}, + {WarningCode::WarnRpcClio, "This is a clio server. clio only serves validated data. If you want to talk to rippled, " "include " "'ledger_index':'current' in your request"}, - {WarnRpcOutdated, "This server may be out of date"}, - {WarnRpcRateLimit, "You are about to be rate limited"}, - {WarnRpcDeprecated, + {WarningCode::WarnRpcOutdated, "This server may be out of date"}, + {WarningCode::WarnRpcRateLimit, "You are about to be rate limited"}, + {WarningCode::WarnRpcDeprecated, "Some fields from your request are deprecated. Please check the documentation at " "https://xrpl.org/docs/references/http-websocket-apis/ and update your request."} }; @@ -85,7 +85,7 @@ makeWarning(WarningCode code) { auto json = boost::json::object{}; auto const& info = getWarningInfo(code); - json["id"] = code; + json["id"] = static_cast(code); json["message"] = info.message; return json; } @@ -220,7 +220,7 @@ makeError(Status const& status) ); if (status.extraInfo) { - for (auto& [key, value] : status.extraInfo.value()) + for (auto& [key, value] : *status.extraInfo) res[key] = value; } diff --git a/src/rpc/Errors.hpp b/src/rpc/Errors.hpp index 7acfe4116..5da04323e 100644 --- a/src/rpc/Errors.hpp +++ b/src/rpc/Errors.hpp @@ -178,6 +178,7 @@ struct Status { }; /** @brief Warning codes that can be returned by clio. */ +// NOLINTNEXTLINE(cppcoreguidelines-use-enum-class) enum WarningCode { WarnUnknown = -1, WarnRpcClio = 2001, @@ -200,7 +201,7 @@ struct WarningInfo { { } - WarningCode code = WarnUnknown; + WarningCode code = WarningCode::WarnUnknown; std::string_view const message = "unknown warning"; }; @@ -223,7 +224,7 @@ public: * * @return The error message */ - char const* + [[nodiscard]] char const* what() const throw() override { return msg_.c_str(); @@ -249,7 +250,7 @@ public: * * @return The error message */ - char const* + [[nodiscard]] char const* what() const throw() override { return account_.c_str(); diff --git a/src/rpc/RPCEngine.hpp b/src/rpc/RPCEngine.hpp index 441db1591..a3e970d30 100644 --- a/src/rpc/RPCEngine.hpp +++ b/src/rpc/RPCEngine.hpp @@ -142,7 +142,7 @@ public: if (not ctx.isAdmin and responseCache_) { if (auto res = responseCache_->get(ctx.method); res.has_value()) - return Result{std::move(res).value()}; + return Result{*std::move(res)}; } if (backend_->isTooBusy()) { @@ -167,7 +167,7 @@ public: .clientIp = ctx.clientIp, .apiVersion = ctx.apiVersion }; - auto v = (*method).process(ctx.params, context); + auto v = method->process(ctx.params, context); LOG(perfLog_.debug()) << ctx.tag() << " finish executing rpc `" << ctx.method << '`'; @@ -321,7 +321,7 @@ public: } private: - bool + [[nodiscard]] bool validHandler(std::string const& method) const { return handlerProvider_->contains(method) || forwardingProxy_.isProxied(method); @@ -352,7 +352,7 @@ private: .clientIp = ctx.clientIp, .apiVersion = ctx.apiVersion }; - auto v = (*method).process(ctx.params, context); + auto v = method->process(ctx.params, context); LOG(perfLog_.debug()) << ctx.tag() << " finish executing rpc `" << ctx.method << '`'; diff --git a/src/rpc/RPCHelpers.cpp b/src/rpc/RPCHelpers.cpp index 0e48d800f..5a389f7e2 100644 --- a/src/rpc/RPCHelpers.cpp +++ b/src/rpc/RPCHelpers.cpp @@ -359,6 +359,8 @@ insertMPTIssuanceID( auto const id = getMPTIssuanceID(meta); ASSERT(id.has_value(), "MPTIssuanceID must have value"); + if (!id) + return false; // For mpttokenissuance create, add mpt_issuance_id to metajson // Otherwise, add it to txn json @@ -630,6 +632,8 @@ traverseNFTObjects( return AccountCursor{.index = nftPreviousPage, .hint = count}; page = backend.fetchLedgerObject(nftPreviousPage, sequence, yield); + if (!page) + break; pageSLE = ripple::SLE{ripple::SerialIter{page->data(), page->size()}, nftPreviousPage}; } diff --git a/src/rpc/WorkQueue.cpp b/src/rpc/WorkQueue.cpp index f4e4b672e..89a72872d 100644 --- a/src/rpc/WorkQueue.cpp +++ b/src/rpc/WorkQueue.cpp @@ -187,14 +187,16 @@ WorkQueue::executeTask(boost::asio::yield_context yield) ); auto const takenAt = std::chrono::system_clock::now(); auto const waited = - std::chrono::duration_cast(takenAt - taskWithTimestamp->queuedAt) + std::chrono::duration_cast( + takenAt - taskWithTimestamp->queuedAt // NOLINT(bugprone-unchecked-optional-access) + ) .count(); ++queued_.get(); durationUs_.get() += waited; LOG(log_.info()) << "WorkQueue wait time: " << waited << ", queue size: " << size(); - taskWithTimestamp->task(yield); + taskWithTimestamp->task(yield); // NOLINT(bugprone-unchecked-optional-access) --curSize_.get(); } diff --git a/src/rpc/common/APIVersion.hpp b/src/rpc/common/APIVersion.hpp index 7ed56255e..faca665a4 100644 --- a/src/rpc/common/APIVersion.hpp +++ b/src/rpc/common/APIVersion.hpp @@ -36,7 +36,7 @@ public: * @param request A JSON object representing the request * @return The specified API version if contained in the JSON object; error string otherwise */ - std::expected virtual parse( + [[nodiscard]] std::expected virtual parse( boost::json::object const& request ) const = 0; }; diff --git a/src/rpc/common/HandlerProvider.hpp b/src/rpc/common/HandlerProvider.hpp index 44e18829c..0174cc213 100644 --- a/src/rpc/common/HandlerProvider.hpp +++ b/src/rpc/common/HandlerProvider.hpp @@ -20,7 +20,7 @@ public: * @param command The method to check for * @return true if the provider contains a handler for the method, false otherwise */ - virtual bool + [[nodiscard]] virtual bool contains(std::string const& command) const = 0; /** @@ -29,7 +29,7 @@ public: * @param command The method to get the handler for * @return The handler for the method, or std::nullopt if the method is not found */ - virtual std::optional + [[nodiscard]] virtual std::optional getHandler(std::string const& command) const = 0; /** @@ -38,7 +38,7 @@ public: * @param command The method to check * @return true if the method is Clio-only, false otherwise */ - virtual bool + [[nodiscard]] virtual bool isClioOnly(std::string const& command) const = 0; }; diff --git a/src/rpc/common/MetaProcessors.hpp b/src/rpc/common/MetaProcessors.hpp index b68568f56..09cf383a8 100644 --- a/src/rpc/common/MetaProcessors.hpp +++ b/src/rpc/common/MetaProcessors.hpp @@ -108,7 +108,7 @@ public: ...); if (firstFailure) - return Error{firstFailure.value()}; + return Error{*firstFailure}; return {}; } diff --git a/src/rpc/common/Types.hpp b/src/rpc/common/Types.hpp index fbf190de1..159f19c6b 100644 --- a/src/rpc/common/Types.hpp +++ b/src/rpc/common/Types.hpp @@ -157,7 +157,7 @@ struct AccountCursor { * * @return The string representation of the cursor */ - std::string + [[nodiscard]] std::string toString() const { return ripple::strHex(index) + "," + std::to_string(hint); @@ -168,7 +168,7 @@ struct AccountCursor { * * @return true if the cursor is non-zero, false otherwise */ - bool + [[nodiscard]] bool isNonZero() const { return index.isNonZero() || hint != 0; diff --git a/src/rpc/common/impl/APIVersionParser.hpp b/src/rpc/common/impl/APIVersionParser.hpp index 5ffde7bbd..4edbf4cf7 100644 --- a/src/rpc/common/impl/APIVersionParser.hpp +++ b/src/rpc/common/impl/APIVersionParser.hpp @@ -28,22 +28,22 @@ public: ProductionAPIVersionParser(util::config::ObjectView const& config); - std::expected + [[nodiscard]] std::expected parse(boost::json::object const& request) const override; - uint32_t + [[nodiscard]] uint32_t getDefaultVersion() const { return defaultVersion_; } - uint32_t + [[nodiscard]] uint32_t getMinVersion() const { return minVersion_; } - uint32_t + [[nodiscard]] uint32_t getMaxVersion() const { return maxVersion_; diff --git a/src/rpc/common/impl/Factories.hpp b/src/rpc/common/impl/Factories.hpp index 472eb64eb..b0b107984 100644 --- a/src/rpc/common/impl/Factories.hpp +++ b/src/rpc/common/impl/Factories.hpp @@ -76,7 +76,7 @@ makeFieldChecker(std::string const& key, Checks&&... checks) ( [&j, &key, &warnings, req = &checks]() { if (auto res = req->check(j, key); res) - warnings.push_back(std::move(res).value()); + warnings.push_back(*std::move(res)); }(), ...); return warnings; diff --git a/src/rpc/common/impl/ForwardingProxy.hpp b/src/rpc/common/impl/ForwardingProxy.hpp index b025d2abb..29d06d727 100644 --- a/src/rpc/common/impl/ForwardingProxy.hpp +++ b/src/rpc/common/impl/ForwardingProxy.hpp @@ -36,7 +36,7 @@ public: { } - bool + [[nodiscard]] bool shouldForward(web::Context const& ctx) const { auto const& request = ctx.params; @@ -85,7 +85,7 @@ public: return Result{std::move(res).value()}; } - bool + [[nodiscard]] bool isProxied(std::string const& method) const { return RPCCenter::isForwarded(method); @@ -106,13 +106,13 @@ private: counters_.get().rpcFailedToForward(method); } - bool + [[nodiscard]] bool validHandler(std::string const& method) const { return handlerProvider_->contains(method) || isProxied(method); } - bool + [[nodiscard]] bool isForcedForward(web::Context const& ctx) const { static constexpr auto kFORCE_FORWARD = "force_forward"; diff --git a/src/rpc/common/impl/HandlerProvider.hpp b/src/rpc/common/impl/HandlerProvider.hpp index 05275bff1..a62f5e02b 100644 --- a/src/rpc/common/impl/HandlerProvider.hpp +++ b/src/rpc/common/impl/HandlerProvider.hpp @@ -41,16 +41,16 @@ public: Counters const& counters ); - bool + [[nodiscard]] bool contains(std::string const& command) const override; - std::optional + [[nodiscard]] std::optional getHandler(std::string const& command) const override; - bool + [[nodiscard]] bool isClioOnly(std::string const& command) const override; - std::unordered_set + [[nodiscard]] std::unordered_set handlerNames() const; }; diff --git a/src/rpc/handlers/AMMInfo.cpp b/src/rpc/handlers/AMMInfo.cpp index 6e7169e2b..08c19082b 100644 --- a/src/rpc/handlers/AMMInfo.cpp +++ b/src/rpc/handlers/AMMInfo.cpp @@ -81,13 +81,17 @@ AMMInfoHandler::process(AMMInfoHandler::Input const& input, Context const& ctx) ASSERT(range.has_value(), "AMMInfo's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; if (input.accountID) { auto keylet = keylet::account(*input.accountID); diff --git a/src/rpc/handlers/AMMInfo.hpp b/src/rpc/handlers/AMMInfo.hpp index 760c42aa5..ce3d3d733 100644 --- a/src/rpc/handlers/AMMInfo.hpp +++ b/src/rpc/handlers/AMMInfo.hpp @@ -91,7 +91,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountChannels.cpp b/src/rpc/handlers/AccountChannels.cpp index e0bd79e7c..5fe65856e 100644 --- a/src/rpc/handlers/AccountChannels.cpp +++ b/src/rpc/handlers/AccountChannels.cpp @@ -75,23 +75,30 @@ AccountChannelsHandler::process( auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountChannel's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) return Error{Status{RippledError::rpcACT_NOT_FOUND}}; auto const destAccountID = input.destinationAccount - ? accountFromStringStrict(input.destinationAccount.value()) + ? accountFromStringStrict(*input.destinationAccount) : std::optional{}; Output response; @@ -107,7 +114,7 @@ AccountChannelsHandler::process( auto const expectedNext = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, input.limit, input.marker, @@ -123,7 +130,7 @@ AccountChannelsHandler::process( response.ledgerHash = ripple::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; - auto const nextMarker = expectedNext.value(); + auto const nextMarker = *expectedNext; if (nextMarker.isNonZero()) response.marker = nextMarker.toString(); @@ -180,7 +187,7 @@ tag_invoke( }; if (output.marker) - obj[JS(marker)] = output.marker.value(); + obj[JS(marker)] = *output.marker; jv = std::move(obj); } diff --git a/src/rpc/handlers/AccountChannels.hpp b/src/rpc/handlers/AccountChannels.hpp index f74d4ba0f..07a197f64 100644 --- a/src/rpc/handlers/AccountChannels.hpp +++ b/src/rpc/handlers/AccountChannels.hpp @@ -127,7 +127,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountCurrencies.cpp b/src/rpc/handlers/AccountCurrencies.cpp index e023e2856..fa5ae30a0 100644 --- a/src/rpc/handlers/AccountCurrencies.cpp +++ b/src/rpc/handlers/AccountCurrencies.cpp @@ -33,17 +33,24 @@ AccountCurrenciesHandler::process( auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountCurrencies' ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) return Error{Status{RippledError::rpcACT_NOT_FOUND}}; @@ -74,7 +81,7 @@ AccountCurrenciesHandler::process( // traverse all owned nodes, limit->max, marker->empty traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, std::numeric_limits::max(), {}, diff --git a/src/rpc/handlers/AccountCurrencies.hpp b/src/rpc/handlers/AccountCurrencies.hpp index 8cef445a4..91ca3a053 100644 --- a/src/rpc/handlers/AccountCurrencies.hpp +++ b/src/rpc/handlers/AccountCurrencies.hpp @@ -90,7 +90,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountInfo.cpp b/src/rpc/handlers/AccountInfo.cpp index f0535c173..ad2470dbc 100644 --- a/src/rpc/handlers/AccountInfo.cpp +++ b/src/rpc/handlers/AccountInfo.cpp @@ -47,16 +47,21 @@ AccountInfoHandler::process(AccountInfoHandler::Input const& input, Context cons auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountInfo's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountStr = input.account.value_or(input.ident.value_or("")); auto const accountID = accountFromStringStrict(accountStr); - auto const accountKeylet = ripple::keylet::account(*accountID); + auto const accountKeylet = + ripple::keylet::account(*accountID); // NOLINT(bugprone-unchecked-optional-access) auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject(accountKeylet.key, lgrInfo.seq, ctx.yield); @@ -94,7 +99,8 @@ AccountInfoHandler::process(AccountInfoHandler::Input const& input, Context cons if (input.signerLists) { // We put the SignerList in an array because of an anticipated // future when we support multiple signer lists on one account. - auto const signersKey = ripple::keylet::signers(*accountID); + auto const signersKey = + ripple::keylet::signers(*accountID); // NOLINT(bugprone-unchecked-optional-access) // This code will need to be revisited if in the future we // support multiple SignerLists on one account. @@ -184,8 +190,8 @@ tag_invoke( if (output.signerLists) { auto signers = boost::json::array(); std::transform( - std::cbegin(output.signerLists.value()), - std::cend(output.signerLists.value()), + std::cbegin(*output.signerLists), + std::cend(*output.signerLists), std::back_inserter(signers), [](auto const& signerList) { return toJson(signerList); } ); diff --git a/src/rpc/handlers/AccountInfo.hpp b/src/rpc/handlers/AccountInfo.hpp index 3f98ead45..84e3c3e51 100644 --- a/src/rpc/handlers/AccountInfo.hpp +++ b/src/rpc/handlers/AccountInfo.hpp @@ -111,7 +111,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountLines.cpp b/src/rpc/handlers/AccountLines.cpp index 92091b594..352c84158 100644 --- a/src/rpc/handlers/AccountLines.cpp +++ b/src/rpc/handlers/AccountLines.cpp @@ -124,16 +124,23 @@ AccountLinesHandler::process(AccountLinesHandler::Input const& input, Context co auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountLines' ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (not accountLedgerObject) @@ -163,7 +170,7 @@ AccountLinesHandler::process(AccountLinesHandler::Input const& input, Context co auto const expectedNext = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, input.limit, input.marker, @@ -174,7 +181,7 @@ AccountLinesHandler::process(AccountLinesHandler::Input const& input, Context co if (not expectedNext.has_value()) return Error{expectedNext.error()}; - auto const nextMarker = expectedNext.value(); + auto const nextMarker = *expectedNext; response.account = input.account; response.limit = input.limit; // not documented, @@ -238,7 +245,7 @@ tag_invoke( }; if (output.marker) - obj[JS(marker)] = output.marker.value(); + obj[JS(marker)] = *output.marker; jv = std::move(obj); } diff --git a/src/rpc/handlers/AccountLines.hpp b/src/rpc/handlers/AccountLines.hpp index 3a59d0b7c..0cd3384e0 100644 --- a/src/rpc/handlers/AccountLines.hpp +++ b/src/rpc/handlers/AccountLines.hpp @@ -143,7 +143,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountMPTokenIssuances.cpp b/src/rpc/handlers/AccountMPTokenIssuances.cpp index 2b07de771..671ba38db 100644 --- a/src/rpc/handlers/AccountMPTokenIssuances.cpp +++ b/src/rpc/handlers/AccountMPTokenIssuances.cpp @@ -106,16 +106,23 @@ AccountMPTokenIssuancesHandler::process( auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountMPTokenIssuances' ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (not accountLedgerObject.has_value()) @@ -132,7 +139,7 @@ AccountMPTokenIssuancesHandler::process( auto const expectedNext = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, input.limit, input.marker, @@ -143,7 +150,7 @@ AccountMPTokenIssuancesHandler::process( if (not expectedNext.has_value()) return Error{expectedNext.error()}; - auto const nextMarker = expectedNext.value(); + auto const nextMarker = *expectedNext; response.account = input.account; response.limit = input.limit; diff --git a/src/rpc/handlers/AccountMPTokenIssuances.hpp b/src/rpc/handlers/AccountMPTokenIssuances.hpp index 3c3ca069d..53ec3c5bf 100644 --- a/src/rpc/handlers/AccountMPTokenIssuances.hpp +++ b/src/rpc/handlers/AccountMPTokenIssuances.hpp @@ -145,7 +145,7 @@ public: * @param ctx The context of the request. * @return The result of the operation. */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountMPTokens.cpp b/src/rpc/handlers/AccountMPTokens.cpp index 19768a235..ddec96c9e 100644 --- a/src/rpc/handlers/AccountMPTokens.cpp +++ b/src/rpc/handlers/AccountMPTokens.cpp @@ -63,16 +63,23 @@ AccountMPTokensHandler::process( auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountMPTokens' ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (not accountLedgerObject.has_value()) @@ -89,7 +96,7 @@ AccountMPTokensHandler::process( auto const expectedNext = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, input.limit, input.marker, @@ -100,7 +107,7 @@ AccountMPTokensHandler::process( if (not expectedNext.has_value()) return Error{expectedNext.error()}; - auto const& nextMarker = expectedNext.value(); + auto const& nextMarker = *expectedNext; response.account = input.account; response.limit = input.limit; diff --git a/src/rpc/handlers/AccountMPTokens.hpp b/src/rpc/handlers/AccountMPTokens.hpp index aef576238..92338b37f 100644 --- a/src/rpc/handlers/AccountMPTokens.hpp +++ b/src/rpc/handlers/AccountMPTokens.hpp @@ -123,7 +123,7 @@ public: * @param ctx The context of the request. * @return The result of the operation. */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountNFTs.cpp b/src/rpc/handlers/AccountNFTs.cpp index c85cf95b2..2ad1ab842 100644 --- a/src/rpc/handlers/AccountNFTs.cpp +++ b/src/rpc/handlers/AccountNFTs.cpp @@ -36,16 +36,23 @@ AccountNFTsHandler::process(AccountNFTsHandler::Input const& input, Context cons auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountNFT's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) @@ -59,6 +66,7 @@ AccountNFTsHandler::process(AccountNFTsHandler::Input const& input, Context cons // if a marker was passed, start at the page specified in marker. Else, start at the max page auto const pageKey = input.marker ? ripple::uint256{input.marker->c_str()} + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) : ripple::keylet::nftpage_max(*accountID).key; auto const blob = sharedPtrBackend_->fetchLedgerObject(pageKey, lgrInfo.seq, ctx.yield); @@ -113,6 +121,7 @@ AccountNFTsHandler::process(AccountNFTsHandler::Input const& input, Context cons auto const nextBlob = sharedPtrBackend_->fetchLedgerObject(nextKey.key, lgrInfo.seq, ctx.yield); page.emplace( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) ripple::SLE{ripple::SerialIter{nextBlob->data(), nextBlob->size()}, nextKey.key} ); } else { diff --git a/src/rpc/handlers/AccountNFTs.hpp b/src/rpc/handlers/AccountNFTs.hpp index 483071f22..79b10a6c1 100644 --- a/src/rpc/handlers/AccountNFTs.hpp +++ b/src/rpc/handlers/AccountNFTs.hpp @@ -99,7 +99,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountObjects.cpp b/src/rpc/handlers/AccountObjects.cpp index 8a29eb9e3..ed0dcae85 100644 --- a/src/rpc/handlers/AccountObjects.cpp +++ b/src/rpc/handlers/AccountObjects.cpp @@ -37,16 +37,23 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountObject's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) @@ -73,9 +80,8 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex Output response; auto const addToResponse = [&](ripple::SLE&& sle) { if (not typeFilter or - std::find( - std::begin(typeFilter.value()), std::end(typeFilter.value()), sle.getType() - ) != std::end(typeFilter.value())) { + std::find(std::begin(*typeFilter), std::end(*typeFilter), sle.getType()) != + std::end(*typeFilter)) { response.accountObjects.push_back(std::move(sle)); } return true; @@ -83,7 +89,7 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex auto const expectedNext = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, input.limit, input.marker, @@ -100,7 +106,7 @@ AccountObjectsHandler::process(AccountObjectsHandler::Input const& input, Contex response.limit = input.limit; response.account = input.account; - auto const& nextMarker = expectedNext.value(); + auto const& nextMarker = *expectedNext; if (nextMarker.isNonZero()) response.marker = nextMarker.toString(); diff --git a/src/rpc/handlers/AccountObjects.hpp b/src/rpc/handlers/AccountObjects.hpp index d88f672e5..5271d3f3a 100644 --- a/src/rpc/handlers/AccountObjects.hpp +++ b/src/rpc/handlers/AccountObjects.hpp @@ -108,7 +108,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountOffers.cpp b/src/rpc/handlers/AccountOffers.cpp index 5b39e105a..a5531d810 100644 --- a/src/rpc/handlers/AccountOffers.cpp +++ b/src/rpc/handlers/AccountOffers.cpp @@ -53,23 +53,30 @@ AccountOffersHandler::process(AccountOffersHandler::Input const& input, Context auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountOffer's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) return Error{Status{RippledError::rpcACT_NOT_FOUND}}; Output response; - response.account = ripple::to_string(*accountID); + response.account = ripple::to_string(*accountID); // NOLINT(bugprone-unchecked-optional-access) response.ledgerHash = ripple::strHex(lgrInfo.hash); response.ledgerIndex = lgrInfo.seq; @@ -82,7 +89,7 @@ AccountOffersHandler::process(AccountOffersHandler::Input const& input, Context auto const expectedNext = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, input.limit, input.marker, @@ -93,7 +100,7 @@ AccountOffersHandler::process(AccountOffersHandler::Input const& input, Context if (not expectedNext.has_value()) return Error{expectedNext.error()}; - auto const nextMarker = expectedNext.value(); + auto const nextMarker = *expectedNext; if (nextMarker.isNonZero()) response.marker = nextMarker.toString(); diff --git a/src/rpc/handlers/AccountOffers.hpp b/src/rpc/handlers/AccountOffers.hpp index aad4f0be5..a4bb11719 100644 --- a/src/rpc/handlers/AccountOffers.hpp +++ b/src/rpc/handlers/AccountOffers.hpp @@ -115,7 +115,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/AccountTx.cpp b/src/rpc/handlers/AccountTx.cpp index 985e1d06f..70f52217f 100644 --- a/src/rpc/handlers/AccountTx.cpp +++ b/src/rpc/handlers/AccountTx.cpp @@ -38,12 +38,14 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "AccountTX's ledger range must be available"); - auto [minIndex, maxIndex] = *range; + auto [minIndex, maxIndex] = *range; // NOLINT(bugprone-unchecked-optional-access) if (input.ledgerIndexMin) { if (ctx.apiVersion > 1u && - (input.ledgerIndexMin > range->maxSequence || - input.ledgerIndexMin < range->minSequence)) { + (input.ledgerIndexMin > + range->maxSequence || // NOLINT(bugprone-unchecked-optional-access) + input.ledgerIndexMin < + range->minSequence)) { // NOLINT(bugprone-unchecked-optional-access) return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMinOutOfRange"}}; } @@ -53,8 +55,10 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c if (input.ledgerIndexMax) { if (ctx.apiVersion > 1u && - (input.ledgerIndexMax > range->maxSequence || - input.ledgerIndexMax < range->minSequence)) { + (input.ledgerIndexMax > + range->maxSequence || // NOLINT(bugprone-unchecked-optional-access) + input.ledgerIndexMax < + range->minSequence)) { // NOLINT(bugprone-unchecked-optional-access) return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMaxOutOfRange"}}; } @@ -84,13 +88,13 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c ctx.yield, input.ledgerHash, input.ledgerIndex, - range->maxSequence + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - maxIndex = minIndex = expectedLgrInfo.value().seq; + maxIndex = minIndex = expectedLgrInfo->seq; } } @@ -146,7 +150,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c if (txn.contains(JS(TransactionType)) && input.transactionTypeInLowercase.has_value() && util::toLower(boost::json::value_to(txn[JS(TransactionType)])) != - input.transactionTypeInLowercase.value()) + *input.transactionTypeInLowercase) continue; if (!input.binary) { @@ -166,7 +170,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c if (auto const& ctid = rpc::encodeCTID(txnPlusMeta.ledgerSequence, txnIdx, networkID); ctid) - obj[txKey].as_object()[JS(ctid)] = ctid.value(); + obj[txKey].as_object()[JS(ctid)] = *ctid; } obj[txKey].as_object()[JS(date)] = txnPlusMeta.date; @@ -201,7 +205,7 @@ AccountTxHandler::process(AccountTxHandler::Input const& input, Context const& c } response.limit = input.limit; - response.account = ripple::to_string(*accountID); + response.account = ripple::to_string(*accountID); // NOLINT(bugprone-unchecked-optional-access) response.ledgerIndexMin = minIndex; response.ledgerIndexMax = maxIndex; diff --git a/src/rpc/handlers/AccountTx.hpp b/src/rpc/handlers/AccountTx.hpp index b26b8be18..10df1a3a6 100644 --- a/src/rpc/handlers/AccountTx.hpp +++ b/src/rpc/handlers/AccountTx.hpp @@ -161,7 +161,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/BookChanges.cpp b/src/rpc/handlers/BookChanges.cpp index 933f831a7..d9012f6cf 100644 --- a/src/rpc/handlers/BookChanges.cpp +++ b/src/rpc/handlers/BookChanges.cpp @@ -29,13 +29,17 @@ BookChangesHandler::process(BookChangesHandler::Input const& input, Context cons ASSERT(range.has_value(), "BookChanges' ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const transactions = sharedPtrBackend_->fetchAllTransactionsInLedger(lgrInfo.seq, ctx.yield); diff --git a/src/rpc/handlers/BookChanges.hpp b/src/rpc/handlers/BookChanges.hpp index 68181ff07..5abf22e93 100644 --- a/src/rpc/handlers/BookChanges.hpp +++ b/src/rpc/handlers/BookChanges.hpp @@ -85,7 +85,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/BookOffers.cpp b/src/rpc/handlers/BookOffers.cpp index 452309629..3522ac5e9 100644 --- a/src/rpc/handlers/BookOffers.cpp +++ b/src/rpc/handlers/BookOffers.cpp @@ -37,14 +37,18 @@ BookOffersHandler::process(Input const& input, Context const& ctx) const ASSERT(range.has_value(), "BookOffer's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); - auto const book = bookMaybe.value(); + auto const& lgrInfo = *expectedLgrInfo; + auto const book = *bookMaybe; auto const bookKey = getBookBase(book); // TODO: Add performance metrics if needed in future diff --git a/src/rpc/handlers/BookOffers.hpp b/src/rpc/handlers/BookOffers.hpp index e5c7f313f..b974d6420 100644 --- a/src/rpc/handlers/BookOffers.hpp +++ b/src/rpc/handlers/BookOffers.hpp @@ -161,7 +161,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/DepositAuthorized.cpp b/src/rpc/handlers/DepositAuthorized.cpp index e80f55539..15bb3ba23 100644 --- a/src/rpc/handlers/DepositAuthorized.cpp +++ b/src/rpc/handlers/DepositAuthorized.cpp @@ -40,23 +40,31 @@ DepositAuthorizedHandler::process( ASSERT(range.has_value(), "DepositAuthorized ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const sourceAccountID = accountFromStringStrict(input.sourceAccount); auto const destinationAccountID = accountFromStringStrict(input.destinationAccount); auto const srcAccountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*sourceAccountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*sourceAccountID).key, + lgrInfo.seq, + ctx.yield ); if (!srcAccountLedgerObject) return Error{Status{RippledError::rpcSRC_ACT_NOT_FOUND, "source_accountNotFound"}}; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const dstKeylet = ripple::keylet::account(*destinationAccountID).key; auto const dstAccountLedgerObject = sharedPtrBackend_->fetchLedgerObject(dstKeylet, lgrInfo.seq, ctx.yield); @@ -75,20 +83,24 @@ DepositAuthorizedHandler::process( ripple::STArray authCreds; if (credentialsPresent) { - if (creds.value().empty()) { + if (creds->empty()) { return Error{ Status{RippledError::rpcINVALID_PARAMS, "credential array has no elements."} }; } - if (creds.value().size() > ripple::maxCredentialsArraySize) { + if (creds->size() > ripple::maxCredentialsArraySize) { return Error{Status{RippledError::rpcINVALID_PARAMS, "credential array too long."}}; } auto const credArray = credentials::fetchCredentialArray( - input.credentials, *sourceAccountID, *sharedPtrBackend_, lgrInfo, ctx.yield + input.credentials, + *sourceAccountID, // NOLINT(bugprone-unchecked-optional-access) + *sharedPtrBackend_, + lgrInfo, + ctx.yield ); if (!credArray.has_value()) return Error{std::move(credArray).error()}; - authCreds = std::move(credArray).value(); + authCreds = *std::move(credArray); } // If the two accounts are the same OR if that flag is @@ -104,8 +116,10 @@ DepositAuthorizedHandler::process( "should already be checked above that there is no duplicate" ); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) hashKey = ripple::keylet::depositPreauth(*destinationAccountID, sortedAuthCreds).key; } else { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) hashKey = ripple::keylet::depositPreauth(*destinationAccountID, *sourceAccountID).key; } @@ -119,7 +133,7 @@ DepositAuthorizedHandler::process( response.ledgerIndex = lgrInfo.seq; response.depositAuthorized = depositAuthorized; if (credentialsPresent) - response.credentials = input.credentials.value(); + response.credentials = *input.credentials; return response; } diff --git a/src/rpc/handlers/DepositAuthorized.hpp b/src/rpc/handlers/DepositAuthorized.hpp index 93f55bdc0..a0db152d2 100644 --- a/src/rpc/handlers/DepositAuthorized.hpp +++ b/src/rpc/handlers/DepositAuthorized.hpp @@ -103,7 +103,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/Feature.cpp b/src/rpc/handlers/Feature.cpp index 663593a26..e3098e994 100644 --- a/src/rpc/handlers/Feature.cpp +++ b/src/rpc/handlers/Feature.cpp @@ -41,19 +41,22 @@ FeatureHandler::process(FeatureHandler::Input const& input, Context const& ctx) ASSERT(range.has_value(), "Feature's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const& all = amendmentCenter_->getAll(); auto searchPredicate = [search = input.feature](auto const& feature) { if (search) { - return ripple::to_string(feature.feature) == search.value() or - feature.name == search.value(); + return ripple::to_string(feature.feature) == *search or feature.name == *search; } return true; }; diff --git a/src/rpc/handlers/Feature.hpp b/src/rpc/handlers/Feature.hpp index 07a2d8b9a..afda786df 100644 --- a/src/rpc/handlers/Feature.hpp +++ b/src/rpc/handlers/Feature.hpp @@ -92,7 +92,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process( Input const& input, Context const& ctx diff --git a/src/rpc/handlers/GatewayBalances.cpp b/src/rpc/handlers/GatewayBalances.cpp index 665c1224c..6509382ad 100644 --- a/src/rpc/handlers/GatewayBalances.cpp +++ b/src/rpc/handlers/GatewayBalances.cpp @@ -47,17 +47,24 @@ GatewayBalancesHandler::process( ASSERT(range.has_value(), "GatewayBalances' ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; // check account - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*accountID).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*accountID).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) @@ -148,7 +155,7 @@ GatewayBalancesHandler::process( // traverse all owned nodes, limit->max, marker->empty auto const ret = traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, std::numeric_limits::max(), {}, @@ -252,6 +259,7 @@ tag_invoke(boost::json::value_to_tag, boost::json if (jsonObject.contains(JS(hotwallet))) { if (jsonObject.at(JS(hotwallet)).is_string()) { input.hotWallets.insert( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) *accountFromStringStrict(boost::json::value_to(jv.at(JS(hotwallet)))) ); } else { diff --git a/src/rpc/handlers/GatewayBalances.hpp b/src/rpc/handlers/GatewayBalances.hpp index 13ebc6a6a..df5c1f668 100644 --- a/src/rpc/handlers/GatewayBalances.hpp +++ b/src/rpc/handlers/GatewayBalances.hpp @@ -151,7 +151,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/GetAggregatePrice.cpp b/src/rpc/handlers/GetAggregatePrice.cpp index 0f5422371..44cdc464f 100644 --- a/src/rpc/handlers/GetAggregatePrice.cpp +++ b/src/rpc/handlers/GetAggregatePrice.cpp @@ -49,13 +49,17 @@ GetAggregatePriceHandler::process( ASSERT(range.has_value(), "GetAggregatePrice's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; // sorted descending by lastUpdateTime, ascending by AssetPrice using TimestampPricesBiMap = boost::bimaps::bimap< @@ -268,6 +272,7 @@ tag_invoke(boost::json::value_to_tag, boost::js .documentId = boost::json::value_to( oracle.as_object().at(JS(oracle_document_id)) ), + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) .account = *util::parseBase58Wrapper( boost::json::value_to(oracle.as_object().at(JS(account))) ) diff --git a/src/rpc/handlers/GetAggregatePrice.hpp b/src/rpc/handlers/GetAggregatePrice.hpp index 1ef04222c..2b4157c10 100644 --- a/src/rpc/handlers/GetAggregatePrice.hpp +++ b/src/rpc/handlers/GetAggregatePrice.hpp @@ -175,7 +175,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/Ledger.cpp b/src/rpc/handlers/Ledger.cpp index 522720661..7e3f0d2ff 100644 --- a/src/rpc/handlers/Ledger.cpp +++ b/src/rpc/handlers/Ledger.cpp @@ -36,13 +36,17 @@ LedgerHandler::process(LedgerHandler::Input const& input, Context const& ctx) co ASSERT(range.has_value(), "LedgerHandler's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; Output output; output.header = toJson(lgrInfo, input.binary, ctx.apiVersion); diff --git a/src/rpc/handlers/Ledger.hpp b/src/rpc/handlers/Ledger.hpp index 0114aa6b5..ae446cd00 100644 --- a/src/rpc/handlers/Ledger.hpp +++ b/src/rpc/handlers/Ledger.hpp @@ -120,7 +120,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/LedgerData.cpp b/src/rpc/handlers/LedgerData.cpp index 6fefa5ac8..109a96633 100644 --- a/src/rpc/handlers/LedgerData.cpp +++ b/src/rpc/handlers/LedgerData.cpp @@ -47,13 +47,17 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const ASSERT(range.has_value(), "LedgerData's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; Output output; @@ -107,7 +111,7 @@ LedgerDataHandler::process(Input const& input, Context const& ctx) const if (page.cursor) { output.marker = ripple::strHex(*(page.cursor)); } else if (input.outOfOrder) { - output.diffMarker = range->maxSequence; + output.diffMarker = range->maxSequence; // NOLINT(bugprone-unchecked-optional-access) } } diff --git a/src/rpc/handlers/LedgerData.hpp b/src/rpc/handlers/LedgerData.hpp index 31be17bea..d053f7e3d 100644 --- a/src/rpc/handlers/LedgerData.hpp +++ b/src/rpc/handlers/LedgerData.hpp @@ -114,7 +114,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/LedgerEntry.cpp b/src/rpc/handlers/LedgerEntry.cpp index 6a172e4a7..f07a85ad2 100644 --- a/src/rpc/handlers/LedgerEntry.cpp +++ b/src/rpc/handlers/LedgerEntry.cpp @@ -50,25 +50,30 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; } else if (input.accountRoot) { key = ripple::keylet::account( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) *util::parseBase58Wrapper(*(input.accountRoot)) ) .key; } else if (input.did) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::did(*util::parseBase58Wrapper(*(input.did))).key; } else if (input.directory) { auto const expectedkey = composeKeyFromDirectory(*input.directory); if (!expectedkey.has_value()) return Error{expectedkey.error()}; - key = expectedkey.value(); + key = expectedkey.value(); // std::expected, not optional } else if (input.offer) { auto const id = util::parseBase58Wrapper( boost::json::value_to(input.offer->at(JS(account))) ); + + // NOLINTBEGIN(bugprone-unchecked-optional-access) key = ripple::keylet::offer( *id, boost::json::value_to(input.offer->at(JS(seq))) ) .key; + // NOLINTEND(bugprone-unchecked-optional-access) } else if (input.rippleStateAccount) { auto const id1 = util::parseBase58Wrapper(boost::json::value_to( @@ -82,12 +87,14 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons boost::json::value_to(input.rippleStateAccount->at(JS(currency))) ); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::line(*id1, *id2, currency).key; } else if (input.escrow) { auto const id = util::parseBase58Wrapper( boost::json::value_to(input.escrow->at(JS(owner))) ); key = + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) ripple::keylet::escrow(*id, util::integralValueAs(input.escrow->at(JS(seq)))) .key; } else if (input.depositPreauth) { @@ -107,6 +114,7 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons auto const authorized = util::parseBase58Wrapper( boost::json::value_to(input.depositPreauth->at(JS(authorized))) ); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::depositPreauth(*owner, *authorized).key; } else { auto const authorizedCredentials = rpc::credentials::parseAuthorizeCredentials( @@ -120,7 +128,8 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons }}; } - key = ripple::keylet::depositPreauth(owner.value(), authCreds).key; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + key = ripple::keylet::depositPreauth(*owner, authCreds).key; } } else if (input.ticket) { auto const id = util::parseBase58Wrapper( @@ -128,7 +137,8 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons ); key = ripple::getTicketIndex( - *id, util::integralValueAs(input.ticket->at(JS(ticket_seq))) + *id, // NOLINT(bugprone-unchecked-optional-access) + util::integralValueAs(input.ticket->at(JS(ticket_seq))) ); } else if (input.amm) { auto const getIssuerFromJson = [](auto const& assetJson) { @@ -164,18 +174,17 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons key = ripple::keylet::bridge(input.bridge->value(), chainType).key; } else if (input.chainClaimId) { - key = ripple::keylet::xChainClaimID(input.bridge->value(), input.chainClaimId.value()) - .key; + key = ripple::keylet::xChainClaimID(input.bridge->value(), *input.chainClaimId).key; } else { key = ripple::keylet::xChainCreateAccountClaimID( - input.bridge->value(), input.createAccountClaimId.value() + input.bridge->value(), *input.createAccountClaimId ) .key; } } else if (input.oracleNode) { - key = input.oracleNode.value(); + key = *input.oracleNode; } else if (input.credential) { - key = input.credential.value(); + key = *input.credential; } else if (input.mptIssuance) { auto const mptIssuanceID = ripple::uint192{std::string_view(*(input.mptIssuance))}; key = ripple::keylet::mptIssuance(mptIssuanceID).key; @@ -186,24 +195,28 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons auto const mptIssuanceID = ripple::uint192{std::string_view( boost::json::value_to(input.mptoken->at(JS(mpt_issuance_id))) )}; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::mptoken(mptIssuanceID, *holder).key; } else if (input.permissionedDomain) { auto const account = ripple::parseBase58( boost::json::value_to(input.permissionedDomain->at(JS(account))) ); auto const seq = util::integralValueAs(input.permissionedDomain->at(JS(seq))); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::permissionedDomain(*account, seq).key; } else if (input.vault) { auto const account = ripple::parseBase58( boost::json::value_to(input.vault->at(JS(owner))) ); auto const seq = util::integralValueAs(input.vault->at(JS(seq))); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::vault(*account, seq).key; } else if (input.loanBroker) { auto const account = ripple::parseBase58( boost::json::value_to(input.loanBroker->at(JS(owner))) ); auto const seq = util::integralValueAs(input.loanBroker->at(JS(seq))); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::loanbroker(*account, seq).key; } else if (input.loan) { auto const id = ripple::uint256{ @@ -218,6 +231,7 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons auto const authorize = ripple::parseBase58( boost::json::value_to(input.delegate->at(JS(authorize))) ); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) key = ripple::keylet::delegate(*account, *authorize).key; } else { // Must specify 1 of the following fields to indicate what type @@ -230,13 +244,17 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "LedgerEntry's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto output = LedgerEntryHandler::Output{}; auto ledgerObject = sharedPtrBackend_->fetchLedgerObject(key, lgrInfo.seq, ctx.yield); @@ -247,7 +265,7 @@ LedgerEntryHandler::process(LedgerEntryHandler::Input const& input, Context cons sharedPtrBackend_->fetchLedgerObjectSeq(key, lgrInfo.seq, ctx.yield); if (!deletedSeq) return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; - ledgerObject = sharedPtrBackend_->fetchLedgerObject(key, deletedSeq.value() - 1, ctx.yield); + ledgerObject = sharedPtrBackend_->fetchLedgerObject(key, *deletedSeq - 1, ctx.yield); if (!ledgerObject || ledgerObject->empty()) return Error{Status{RippledError::rpcENTRY_NOT_FOUND}}; output.deletedLedgerIndex = deletedSeq; @@ -301,6 +319,7 @@ LedgerEntryHandler::composeKeyFromDirectory(boost::json::object const& directory auto const ownerID = util::parseBase58Wrapper( boost::json::value_to(directory.at(JS(owner))) ); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) return ripple::keylet::page(ripple::keylet::ownerDir(*ownerID), subIndex).key; } @@ -324,7 +343,7 @@ tag_invoke( if (output.nodeBinary) { object[JS(node_binary)] = *(output.nodeBinary); } else { - object[JS(node)] = *(output.node); + object[JS(node)] = *(output.node); // NOLINT(bugprone-unchecked-optional-access) } jv = std::move(object); diff --git a/src/rpc/handlers/LedgerEntry.hpp b/src/rpc/handlers/LedgerEntry.hpp index 0e71ca126..293926468 100644 --- a/src/rpc/handlers/LedgerEntry.hpp +++ b/src/rpc/handlers/LedgerEntry.hpp @@ -560,7 +560,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/LedgerIndex.cpp b/src/rpc/handlers/LedgerIndex.cpp index f957d7397..293de1ae4 100644 --- a/src/rpc/handlers/LedgerIndex.cpp +++ b/src/rpc/handlers/LedgerIndex.cpp @@ -26,7 +26,7 @@ LedgerIndexHandler::process(LedgerIndexHandler::Input const& input, Context cons auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "LedgerIndex's ledger range must be available"); - auto const [minIndex, maxIndex] = *range; + auto const [minIndex, maxIndex] = *range; // NOLINT(bugprone-unchecked-optional-access) auto const fillOutputByIndex = [&](std::uint32_t index) { auto const ledger = sharedPtrBackend_->fetchLedgerBySequence(index, ctx.yield); diff --git a/src/rpc/handlers/LedgerIndex.hpp b/src/rpc/handlers/LedgerIndex.hpp index e913e4a1d..c79a34c29 100644 --- a/src/rpc/handlers/LedgerIndex.hpp +++ b/src/rpc/handlers/LedgerIndex.hpp @@ -77,7 +77,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/LedgerRange.cpp b/src/rpc/handlers/LedgerRange.cpp index 0a01cefad..151b783b9 100644 --- a/src/rpc/handlers/LedgerRange.cpp +++ b/src/rpc/handlers/LedgerRange.cpp @@ -16,7 +16,8 @@ LedgerRangeHandler::Result LedgerRangeHandler::process([[maybe_unused]] Context const& ctx) const { // note: we can't get here if range is not available so it's safe - return Output{sharedPtrBackend_->fetchLedgerRange().value()}; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return Output{*sharedPtrBackend_->fetchLedgerRange()}; } void diff --git a/src/rpc/handlers/LedgerRange.hpp b/src/rpc/handlers/LedgerRange.hpp index 6edad2829..fb0617a12 100644 --- a/src/rpc/handlers/LedgerRange.hpp +++ b/src/rpc/handlers/LedgerRange.hpp @@ -47,7 +47,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Context const& ctx) const; private: diff --git a/src/rpc/handlers/MPTHolders.cpp b/src/rpc/handlers/MPTHolders.cpp index 5e1cba23f..2fdbebd73 100644 --- a/src/rpc/handlers/MPTHolders.cpp +++ b/src/rpc/handlers/MPTHolders.cpp @@ -35,12 +35,16 @@ MPTHoldersHandler::process(MPTHoldersHandler::Input const& input, Context const& ASSERT(range.has_value(), "MPTHolder's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const limit = input.limit.value_or(MPTHoldersHandler::kLIMIT_DEFAULT); auto const mptID = ripple::uint192{input.mptID.c_str()}; diff --git a/src/rpc/handlers/MPTHolders.hpp b/src/rpc/handlers/MPTHolders.hpp index e41474012..22c302f84 100644 --- a/src/rpc/handlers/MPTHolders.hpp +++ b/src/rpc/handlers/MPTHolders.hpp @@ -98,7 +98,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/NFTBuyOffers.hpp b/src/rpc/handlers/NFTBuyOffers.hpp index 1d170499f..37cdf99de 100644 --- a/src/rpc/handlers/NFTBuyOffers.hpp +++ b/src/rpc/handlers/NFTBuyOffers.hpp @@ -32,7 +32,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; }; } // namespace rpc diff --git a/src/rpc/handlers/NFTHistory.cpp b/src/rpc/handlers/NFTHistory.cpp index e2842cc82..8699f99aa 100644 --- a/src/rpc/handlers/NFTHistory.cpp +++ b/src/rpc/handlers/NFTHistory.cpp @@ -37,18 +37,22 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "NFTHistory's ledger range must be available"); - auto [minIndex, maxIndex] = *range; + auto [minIndex, maxIndex] = *range; // NOLINT(bugprone-unchecked-optional-access) if (input.ledgerIndexMin) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) if (range->maxSequence < input.ledgerIndexMin || range->minSequence > input.ledgerIndexMin) return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMinOutOfRange"}}; + // NOLINTEND(bugprone-unchecked-optional-access) minIndex = *input.ledgerIndexMin; } if (input.ledgerIndexMax) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) if (range->maxSequence < input.ledgerIndexMax || range->minSequence > input.ledgerIndexMax) return Error{Status{RippledError::rpcLGR_IDX_MALFORMED, "ledgerSeqMaxOutOfRange"}}; + // NOLINTEND(bugprone-unchecked-optional-access) maxIndex = *input.ledgerIndexMax; } @@ -65,13 +69,17 @@ NFTHistoryHandler::process(NFTHistoryHandler::Input const& input, Context const& } auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - maxIndex = minIndex = expectedLgrInfo.value().seq; + maxIndex = minIndex = expectedLgrInfo->seq; } std::optional cursor; diff --git a/src/rpc/handlers/NFTHistory.hpp b/src/rpc/handlers/NFTHistory.hpp index 0a8588f20..8cc982cc3 100644 --- a/src/rpc/handlers/NFTHistory.hpp +++ b/src/rpc/handlers/NFTHistory.hpp @@ -136,7 +136,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/NFTInfo.cpp b/src/rpc/handlers/NFTInfo.cpp index cac3a8856..6b09c8887 100644 --- a/src/rpc/handlers/NFTInfo.cpp +++ b/src/rpc/handlers/NFTInfo.cpp @@ -32,13 +32,17 @@ NFTInfoHandler::process(NFTInfoHandler::Input const& input, Context const& ctx) ASSERT(range.has_value(), "NFTInfo's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const maybeNft = sharedPtrBackend_->fetchNFT(tokenID, lgrInfo.seq, ctx.yield); if (not maybeNft.has_value()) diff --git a/src/rpc/handlers/NFTInfo.hpp b/src/rpc/handlers/NFTInfo.hpp index c576442c8..2fb1a8e96 100644 --- a/src/rpc/handlers/NFTInfo.hpp +++ b/src/rpc/handlers/NFTInfo.hpp @@ -94,7 +94,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/NFTOffersCommon.cpp b/src/rpc/handlers/NFTOffersCommon.cpp index 46815b616..43fff643a 100644 --- a/src/rpc/handlers/NFTOffersCommon.cpp +++ b/src/rpc/handlers/NFTOffersCommon.cpp @@ -75,13 +75,17 @@ NFTOffersHandlerBase::iterateOfferDirectory( ASSERT(range.has_value(), "NFTOffersCommon's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; // TODO: just check for existence without pulling if (not sharedPtrBackend_->fetchLedgerObject(directory.key, lgrInfo.seq, yield)) diff --git a/src/rpc/handlers/NFTOffersCommon.hpp b/src/rpc/handlers/NFTOffersCommon.hpp index 743a04794..39ca80f16 100644 --- a/src/rpc/handlers/NFTOffersCommon.hpp +++ b/src/rpc/handlers/NFTOffersCommon.hpp @@ -105,7 +105,7 @@ protected: * @param yield The coroutine context * @return The result of the iteration */ - Result + [[nodiscard]] Result iterateOfferDirectory( Input input, ripple::uint256 const& tokenID, diff --git a/src/rpc/handlers/NFTSellOffers.hpp b/src/rpc/handlers/NFTSellOffers.hpp index a1fe7f309..d77f4cd87 100644 --- a/src/rpc/handlers/NFTSellOffers.hpp +++ b/src/rpc/handlers/NFTSellOffers.hpp @@ -32,7 +32,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; }; diff --git a/src/rpc/handlers/NFTsByIssuer.cpp b/src/rpc/handlers/NFTsByIssuer.cpp index f9bc9a2a1..fcd624c77 100644 --- a/src/rpc/handlers/NFTsByIssuer.cpp +++ b/src/rpc/handlers/NFTsByIssuer.cpp @@ -34,18 +34,25 @@ NFTsByIssuerHandler::process(NFTsByIssuerHandler::Input const& input, Context co ASSERT(range.has_value(), "NFTsByIssuer's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const limit = input.limit.value_or(NFTsByIssuerHandler::kLIMIT_DEFAULT); auto const issuer = accountFromStringStrict(input.issuer); auto const accountLedgerObject = sharedPtrBackend_->fetchLedgerObject( - ripple::keylet::account(*issuer).key, lgrInfo.seq, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::account(*issuer).key, + lgrInfo.seq, + ctx.yield ); if (!accountLedgerObject) @@ -56,12 +63,18 @@ NFTsByIssuerHandler::process(NFTsByIssuerHandler::Input const& input, Context co cursor = uint256{input.marker->c_str()}; auto const dbResponse = sharedPtrBackend_->fetchNFTsByIssuer( - *issuer, input.nftTaxon, lgrInfo.seq, limit, cursor, ctx.yield + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *issuer, + input.nftTaxon, + lgrInfo.seq, + limit, + cursor, + ctx.yield ); auto output = NFTsByIssuerHandler::Output{}; - output.issuer = toBase58(*issuer); + output.issuer = toBase58(*issuer); // NOLINT(bugprone-unchecked-optional-access) output.limit = limit; output.ledgerIndex = lgrInfo.seq; output.nftTaxon = input.nftTaxon; diff --git a/src/rpc/handlers/NFTsByIssuer.hpp b/src/rpc/handlers/NFTsByIssuer.hpp index 42ea4bc8a..6765fd180 100644 --- a/src/rpc/handlers/NFTsByIssuer.hpp +++ b/src/rpc/handlers/NFTsByIssuer.hpp @@ -98,7 +98,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/NoRippleCheck.cpp b/src/rpc/handlers/NoRippleCheck.cpp index 00a592c9b..acf6c9e55 100644 --- a/src/rpc/handlers/NoRippleCheck.cpp +++ b/src/rpc/handlers/NoRippleCheck.cpp @@ -43,15 +43,20 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context ASSERT(range.has_value(), "NoRippleCheck's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) return Error{expectedLgrInfo.error()}; - auto const& lgrInfo = expectedLgrInfo.value(); + auto const& lgrInfo = *expectedLgrInfo; auto const accountID = accountFromStringStrict(input.account); - auto const keylet = ripple::keylet::account(*accountID).key; + auto const keylet = + ripple::keylet::account(*accountID).key; // NOLINT(bugprone-unchecked-optional-access) auto const accountObj = sharedPtrBackend_->fetchLedgerObject(keylet, lgrInfo.seq, ctx.yield); if (!accountObj) @@ -88,7 +93,8 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context output.problems.emplace_back("You should immediately set your default ripple flag"); if (input.transactions) { - auto tx = getBaseTx(*accountID, accountSeq++); + auto tx = + getBaseTx(*accountID, accountSeq++); // NOLINT(bugprone-unchecked-optional-access) tx[JS(TransactionType)] = "AccountSet"; tx[JS(SetFlag)] = ripple::asfDefaultRipple; output.transactions->push_back(tx); @@ -99,7 +105,7 @@ NoRippleCheckHandler::process(NoRippleCheckHandler::Input const& input, Context traverseOwnedNodes( *sharedPtrBackend_, - *accountID, + *accountID, // NOLINT(bugprone-unchecked-optional-access) lgrInfo.seq, std::numeric_limits::max(), {}, diff --git a/src/rpc/handlers/NoRippleCheck.hpp b/src/rpc/handlers/NoRippleCheck.hpp index 7976cb106..a8db6a64e 100644 --- a/src/rpc/handlers/NoRippleCheck.hpp +++ b/src/rpc/handlers/NoRippleCheck.hpp @@ -118,7 +118,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/ServerInfo.hpp b/src/rpc/handlers/ServerInfo.hpp index 653984591..95ce881fc 100644 --- a/src/rpc/handlers/ServerInfo.hpp +++ b/src/rpc/handlers/ServerInfo.hpp @@ -167,7 +167,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const { using namespace rpc; @@ -176,7 +176,11 @@ public: auto const range = backend_->fetchLedgerRange(); ASSERT(range.has_value(), "ServerInfo's ledger range must be available"); - auto const lgrInfo = backend_->fetchLedgerBySequence(range->maxSequence, ctx.yield); + auto const lgrInfo = backend_->fetchLedgerBySequence( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + range->maxSequence, + ctx.yield + ); if (not lgrInfo.has_value()) return Error{Status{RippledError::rpcINTERNAL}}; @@ -191,7 +195,9 @@ public: static_cast(lgrInfo->closeTime.time_since_epoch().count()) - static_cast(kRIPPLE_EPOCH_START); + // NOLINTBEGIN(bugprone-unchecked-optional-access) output.info.completeLedgers = fmt::format("{}-{}", range->minSequence, range->maxSequence); + // NOLINTEND(bugprone-unchecked-optional-access) if (ctx.isAdmin) { output.info.adminSection = { @@ -268,7 +274,7 @@ private: jv.as_object()["corruption_detected"] = true; if (info.rippledInfo) { - auto const& rippledInfo = info.rippledInfo.value(); + auto const& rippledInfo = *info.rippledInfo; if (rippledInfo.contains(JS(load_factor))) jv.as_object()[JS(load_factor)] = rippledInfo.at(JS(load_factor)); @@ -298,6 +304,7 @@ private: ValidatedLedgerSection const& validated ) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) jv = { {JS(age), validated.age}, {JS(hash), validated.hash}, @@ -306,6 +313,7 @@ private: {JS(reserve_base_xrp), validated.fees->reserve.decimalXRP()}, {JS(reserve_inc_xrp), validated.fees->increment.decimalXRP()}, }; + // NOLINTEND(bugprone-unchecked-optional-access) } friend void diff --git a/src/rpc/handlers/Subscribe.cpp b/src/rpc/handlers/Subscribe.cpp index cb8098863..8e038e241 100644 --- a/src/rpc/handlers/Subscribe.cpp +++ b/src/rpc/handlers/Subscribe.cpp @@ -166,6 +166,7 @@ SubscribeHandler::subscribeToAccountsProposed( { for (auto const& account : accounts) { auto const accountID = accountFromStringStrict(account); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) subscriptions_->subProposedAccount(*accountID, session); } } @@ -178,6 +179,7 @@ SubscribeHandler::subscribeToAccounts( { for (auto const& account : accounts) { auto const accountID = accountFromStringStrict(account); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) subscriptions_->subAccount(*accountID, session); } } @@ -305,7 +307,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::valu auto const parsedBookMaybe = parseBook(book.as_object()); ASSERT(parsedBookMaybe.has_value(), "Book parsing failed"); - internalBook.book = parsedBookMaybe.value(); + internalBook.book = *parsedBookMaybe; input.books->push_back(internalBook); } } diff --git a/src/rpc/handlers/Subscribe.hpp b/src/rpc/handlers/Subscribe.hpp index 5f9c0083b..5e8d43642 100644 --- a/src/rpc/handlers/Subscribe.hpp +++ b/src/rpc/handlers/Subscribe.hpp @@ -107,11 +107,11 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: - boost::json::object + [[nodiscard]] boost::json::object subscribeToStreams( boost::asio::yield_context yield, std::vector const& streams, diff --git a/src/rpc/handlers/TransactionEntry.cpp b/src/rpc/handlers/TransactionEntry.cpp index ce7ec4a27..d4b4c2c52 100644 --- a/src/rpc/handlers/TransactionEntry.cpp +++ b/src/rpc/handlers/TransactionEntry.cpp @@ -30,7 +30,11 @@ TransactionEntryHandler::process( ASSERT(range.has_value(), "TransactionEntry's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, input.ledgerHash, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + input.ledgerHash, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) @@ -39,7 +43,7 @@ TransactionEntryHandler::process( auto output = TransactionEntryHandler::Output{}; output.apiVersion = ctx.apiVersion; - output.ledgerHeader = expectedLgrInfo.value(); + output.ledgerHeader = *expectedLgrInfo; auto const dbRet = sharedPtrBackend_->fetchTransaction(ripple::uint256{input.txHash.c_str()}, ctx.yield); // Note: transaction_entry is meant to only search a specified ledger for @@ -73,6 +77,8 @@ tag_invoke( ) { auto const metaKey = output.apiVersion > 1u ? JS(meta) : JS(metadata); + + // NOLINTBEGIN(bugprone-unchecked-optional-access) jv = { {JS(validated), output.validated}, {metaKey, output.metadata}, @@ -80,8 +86,10 @@ tag_invoke( {JS(ledger_index), output.ledgerHeader->seq}, {JS(ledger_hash), ripple::strHex(output.ledgerHeader->hash)}, }; + // NOLINTEND(bugprone-unchecked-optional-access) if (output.apiVersion > 1u) { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) jv.as_object()[JS(close_time_iso)] = ripple::to_string_iso(output.ledgerHeader->closeTime); if (output.tx.contains(JS(hash))) { jv.as_object()[JS(hash)] = output.tx.at(JS(hash)); diff --git a/src/rpc/handlers/TransactionEntry.hpp b/src/rpc/handlers/TransactionEntry.hpp index 76d662be1..919893b4e 100644 --- a/src/rpc/handlers/TransactionEntry.hpp +++ b/src/rpc/handlers/TransactionEntry.hpp @@ -94,7 +94,7 @@ public: * @param ctx The context of the request * @return The result of the command */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/Tx.hpp b/src/rpc/handlers/Tx.hpp index 8fd4e11f3..7ae874aca 100644 --- a/src/rpc/handlers/Tx.hpp +++ b/src/rpc/handlers/Tx.hpp @@ -124,7 +124,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const { if (input.ctid && input.transaction) // ambiguous identifier @@ -183,8 +183,11 @@ public: auto const range = sharedPtrBackend_->fetchLedgerRange(); ASSERT(range.has_value(), "Tx's ledger range must be available"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) auto const searchedAll = range->maxSequence >= *input.maxLedger && range->minSequence <= *input.minLedger; + // NOLINTEND(bugprone-unchecked-optional-access) + boost::json::object extra; extra["searched_all"] = searchedAll; @@ -233,7 +236,7 @@ public: } private: - std::optional + [[nodiscard]] std::optional fetchTxViaCtid(uint32_t ledgerSeq, uint32_t txId, boost::asio::yield_context yield) const { auto const txs = sharedPtrBackend_->fetchAllTransactionsInLedger(ledgerSeq, yield); diff --git a/src/rpc/handlers/Unsubscribe.cpp b/src/rpc/handlers/Unsubscribe.cpp index 9fcf1a5d4..41a5b8ea0 100644 --- a/src/rpc/handlers/Unsubscribe.cpp +++ b/src/rpc/handlers/Unsubscribe.cpp @@ -126,6 +126,7 @@ UnsubscribeHandler::unsubscribeFromAccounts( { for (auto const& account : accounts) { auto const accountID = accountFromStringStrict(account); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) subscriptions_->unsubAccount(*accountID, session); } } @@ -138,6 +139,7 @@ UnsubscribeHandler::unsubscribeFromProposedAccounts( { for (auto const& account : accountsProposed) { auto const accountID = accountFromStringStrict(account); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) subscriptions_->unsubProposedAccount(*accountID, session); } } @@ -188,7 +190,7 @@ tag_invoke(boost::json::value_to_tag, boost::json::va auto const parsedBookMaybe = parseBook(book.as_object()); ASSERT(parsedBookMaybe.has_value(), "Invalid book format"); - internalBook.book = parsedBookMaybe.value(); + internalBook.book = *parsedBookMaybe; input.books->push_back(internalBook); } } diff --git a/src/rpc/handlers/Unsubscribe.hpp b/src/rpc/handlers/Unsubscribe.hpp index a16b20549..b41d9e7d0 100644 --- a/src/rpc/handlers/Unsubscribe.hpp +++ b/src/rpc/handlers/Unsubscribe.hpp @@ -76,7 +76,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/VaultInfo.cpp b/src/rpc/handlers/VaultInfo.cpp index 6fc959535..990cf3782 100644 --- a/src/rpc/handlers/VaultInfo.cpp +++ b/src/rpc/handlers/VaultInfo.cpp @@ -68,7 +68,11 @@ VaultInfoHandler::process(VaultInfoHandler::Input const& input, Context const& c ASSERT(range.has_value(), "VaultInfo's ledger range must be available"); auto const expectedLgrInfo = getLedgerHeaderFromHashOrSeq( - *sharedPtrBackend_, ctx.yield, std::nullopt, input.ledgerIndex, range->maxSequence + *sharedPtrBackend_, + ctx.yield, + std::nullopt, + input.ledgerIndex, + range->maxSequence // NOLINT(bugprone-unchecked-optional-access) ); if (not expectedLgrInfo.has_value()) @@ -106,14 +110,13 @@ VaultInfoHandler::process(VaultInfoHandler::Input const& input, Context const& c // Fetch the vault object and it's associated issuance ID auto const vaultLedgerObject = - sharedPtrBackend_->fetchLedgerObject(vaultKeylet.value().key, lgrInfo.seq, ctx.yield); + sharedPtrBackend_->fetchLedgerObject(vaultKeylet->key, lgrInfo.seq, ctx.yield); if (not vaultLedgerObject) return Error{Status{RippledError::rpcENTRY_NOT_FOUND, "vault object not found."}}; ripple::STLedgerEntry const vaultSle{ - ripple::SerialIter{vaultLedgerObject->data(), vaultLedgerObject->size()}, - vaultKeylet.value().key + ripple::SerialIter{vaultLedgerObject->data(), vaultLedgerObject->size()}, vaultKeylet->key }; auto const issuanceKeylet = ripple::keylet::mptIssuance(vaultSle[ripple::sfShareMPTID]).key; diff --git a/src/rpc/handlers/VaultInfo.hpp b/src/rpc/handlers/VaultInfo.hpp index f8ba93a41..aae4af92c 100644 --- a/src/rpc/handlers/VaultInfo.hpp +++ b/src/rpc/handlers/VaultInfo.hpp @@ -93,7 +93,7 @@ public: * @param ctx The context of the request * @return The result of the operation */ - Result + [[nodiscard]] Result process(Input const& input, Context const& ctx) const; private: diff --git a/src/rpc/handlers/VersionHandler.hpp b/src/rpc/handlers/VersionHandler.hpp index 8f82c3307..d470da94c 100644 --- a/src/rpc/handlers/VersionHandler.hpp +++ b/src/rpc/handlers/VersionHandler.hpp @@ -51,7 +51,7 @@ public: * @param ctx The context of the request * @return The result of the command */ - Result + [[nodiscard]] Result process([[maybe_unused]] Context const& ctx) const { using namespace rpc; diff --git a/src/util/BlockingCache.hpp b/src/util/BlockingCache.hpp index 36bbefe01..ca85bb3f2 100644 --- a/src/util/BlockingCache.hpp +++ b/src/util/BlockingCache.hpp @@ -98,7 +98,7 @@ public: case State::HasValue: { auto const value = value_.template lock(); ASSERT(value->has_value(), "Value should be presented when the cache is full"); - return value->value(); + return **value; // NOLINT(bugprone-unchecked-optional-access) } case State::NoValue: { return update(yield, std::move(updater), std::move(verifier)); @@ -127,10 +127,10 @@ public: state_ = State::Updating; auto const result = updater(yield); - auto const shouldBeCached = result.has_value() and verifier(result.value()); + auto const shouldBeCached = result.has_value() and verifier(*result); if (shouldBeCached) { - value_.lock().get() = result.value(); + value_.lock().get() = *result; state_ = State::HasValue; } else { state_ = State::NoValue; @@ -208,7 +208,7 @@ private: if (state_ == State::Updating) { sharedContext->timer.async_wait(yield[errorCode]); ASSERT(sharedContext->result.has_value(), "There should be some value after waiting"); - return std::move(sharedContext->result).value(); + return *std::move(sharedContext->result); // NOLINT(bugprone-unchecked-optional-access) } return asyncGet(yield, std::move(updater), std::move(verifier)); } diff --git a/src/util/Mutex.hpp b/src/util/Mutex.hpp index 1835b7e59..898365d28 100644 --- a/src/util/Mutex.hpp +++ b/src/util/Mutex.hpp @@ -34,7 +34,7 @@ public: return data_; } - ProtectedDataType const& + [[nodiscard]] ProtectedDataType const& get() const { return data_; diff --git a/src/util/ResponseExpirationCache.hpp b/src/util/ResponseExpirationCache.hpp index bd70b57f8..083a2daea 100644 --- a/src/util/ResponseExpirationCache.hpp +++ b/src/util/ResponseExpirationCache.hpp @@ -38,7 +38,7 @@ class ResponseExpirationCache { * * @return The response */ - std::optional + [[nodiscard]] std::optional get() const; /** @@ -46,7 +46,7 @@ class ResponseExpirationCache { * * @return The last time the cache was updated */ - std::chrono::steady_clock::time_point + [[nodiscard]] std::chrono::steady_clock::time_point lastUpdated() const; /** diff --git a/src/util/Retry.cpp b/src/util/Retry.cpp index d49532291..29d2fdba8 100644 --- a/src/util/Retry.cpp +++ b/src/util/Retry.cpp @@ -70,7 +70,7 @@ void Retry::reset() { attemptNumber_ = 0; - strategy_->reset(); + (*strategy_).reset(); } ExponentialBackoffStrategy::ExponentialBackoffStrategy( diff --git a/src/util/Retry.hpp b/src/util/Retry.hpp index 644df5d8c..3064423e2 100644 --- a/src/util/Retry.hpp +++ b/src/util/Retry.hpp @@ -31,7 +31,7 @@ public: /** * @return The current delay value */ - std::chrono::steady_clock::duration + [[nodiscard]] std::chrono::steady_clock::duration getDelay() const; /** @@ -50,7 +50,7 @@ protected: /** * @return The next computed delay value */ - virtual std::chrono::steady_clock::duration + [[nodiscard]] virtual std::chrono::steady_clock::duration nextDelay() const = 0; }; using RetryStrategyPtr = std::unique_ptr; @@ -114,13 +114,13 @@ public: /** * @return The current attempt number */ - size_t + [[nodiscard]] size_t attemptNumber() const; /** * @return The current delay value */ - std::chrono::steady_clock::duration + [[nodiscard]] std::chrono::steady_clock::duration delayValue() const; /** @@ -149,7 +149,7 @@ public: ); private: - std::chrono::steady_clock::duration + [[nodiscard]] std::chrono::steady_clock::duration nextDelay() const override; }; diff --git a/src/util/Taggable.cpp b/src/util/Taggable.cpp index bf89b59b2..0cd3632ce 100644 --- a/src/util/Taggable.cpp +++ b/src/util/Taggable.cpp @@ -21,7 +21,7 @@ UUIDTagGenerator::next() static boost::uuids::random_generator kGEN{}; static std::mutex kMTX{}; - std::lock_guard const lk(kMTX); + std::scoped_lock const lk(kMTX); return kGEN(); } diff --git a/src/util/Taggable.hpp b/src/util/Taggable.hpp index 0a696abd5..ba178b298 100644 --- a/src/util/Taggable.hpp +++ b/src/util/Taggable.hpp @@ -83,7 +83,7 @@ public: * * @return The string representation of the tag */ - std::string + [[nodiscard]] std::string toString() const { std::ostringstream oss; @@ -132,7 +132,7 @@ public: os << "["; if (parent_.has_value()) - (*parent_).get().decorate(os); + parent_->get().decorate(os); os << tag_ << "] "; } @@ -217,7 +217,7 @@ public: * * @return An instance of the requested decorator */ - std::unique_ptr + [[nodiscard]] std::unique_ptr make() const; /** @@ -226,7 +226,7 @@ public: * @param parent The parent tag decorator to use * @return A new instance of the tag decorator factory */ - TagDecoratorFactory + [[nodiscard]] TagDecoratorFactory with(ParentType parent) const noexcept; }; @@ -260,7 +260,7 @@ public: * * @return Reference to the tag decorator */ - BaseTagDecorator const& + [[nodiscard]] BaseTagDecorator const& tag() const { return *tagDecorator_; diff --git a/src/util/async/Operation.hpp b/src/util/async/Operation.hpp index fac217e1f..38afaab17 100644 --- a/src/util/async/Operation.hpp +++ b/src/util/async/Operation.hpp @@ -62,7 +62,7 @@ struct BasicScheduledOperation : util::MoveTracker { void emplace(auto&& op) { - std::lock_guard const lock{m_}; + std::scoped_lock const lock{m_}; op_.emplace(std::forward(op)); ready_.notify_all(); } @@ -72,7 +72,7 @@ struct BasicScheduledOperation : util::MoveTracker { { std::unique_lock lock{m_}; ready_.wait(lock, [this] { return op_.has_value(); }); - return op_.value(); + return *op_; // NOLINT(bugprone-unchecked-optional-access) } }; diff --git a/src/util/async/context/BasicExecutionContext.hpp b/src/util/async/context/BasicExecutionContext.hpp index a02b1df7f..d08de5d99 100644 --- a/src/util/async/context/BasicExecutionContext.hpp +++ b/src/util/async/context/BasicExecutionContext.hpp @@ -64,7 +64,7 @@ struct AsioPoolContext { AsioPoolContext(AsioPoolContext const&) = delete; AsioPoolContext(AsioPoolContext&&) = default; - Strand + [[nodiscard]] Strand makeStrand() const { ASSERT(executor, "Called after executor was moved from."); @@ -85,7 +85,7 @@ struct AsioPoolContext { executor->join(); } - Executor& + [[nodiscard]] Executor& getExecutor() const { ASSERT(executor, "Called after executor was moved from."); diff --git a/src/util/config/ConfigConstraints.hpp b/src/util/config/ConfigConstraints.hpp index 3349ae74f..bf60e50d0 100644 --- a/src/util/config/ConfigConstraints.hpp +++ b/src/util/config/ConfigConstraints.hpp @@ -104,7 +104,7 @@ protected: * @return The error message specifying what the value of key must be */ template - constexpr std::string + [[nodiscard]] constexpr std::string makeErrorMsg( std::string_view key, Value const& value, @@ -129,7 +129,7 @@ protected: * @param val The value type to be checked * @return An Error object if the constraint is not met, nullopt otherwise */ - virtual std::optional + [[nodiscard]] virtual std::optional checkTypeImpl(Value const& val) const = 0; /** @@ -138,7 +138,7 @@ protected: * @param val The value type to be checked * @return An Error object if the constraint is not met, nullopt otherwise */ - virtual std::optional + [[nodiscard]] virtual std::optional checkValueImpl(Value const& val) const = 0; /** diff --git a/src/util/config/ConfigDefinition.cpp b/src/util/config/ConfigDefinition.cpp index 444ddb6ac..e6a51177c 100644 --- a/src/util/config/ConfigDefinition.cpp +++ b/src/util/config/ConfigDefinition.cpp @@ -47,13 +47,13 @@ ClioConfigDefinition::getObject(std::string_view prefix, std::optional(mapVal)) { - ASSERT(std::get(mapVal).size() > idx.value(), "Index provided is out of scope"); + ASSERT(std::get(mapVal).size() > *idx, "Index provided is out of scope"); // we want to support getObject("array") and getObject("array.[]"), so we check if "[]" // exists if (!prefix.contains("[]")) - return ObjectView{prefixWithDot + "[]", idx.value(), *this}; - return ObjectView{prefix, idx.value(), *this}; + return ObjectView{prefixWithDot + "[]", *idx, *this}; + return ObjectView{prefix, *idx, *this}; } if (hasPrefix && !idx.has_value() && !mapKey.contains(prefixWithDot + "[]")) return ObjectView{prefix, *this}; @@ -174,7 +174,7 @@ ClioConfigDefinition::parse(ConfigFileInterface const& config) [&key, &config, &listOfErrors](ConfigValue& val) { if (auto const maybeError = val.setValue(config.getValue(key), key); maybeError.has_value()) { - listOfErrors.emplace_back(maybeError.value()); + listOfErrors.emplace_back(*maybeError); } }, // handle the case where the config value is an array. diff --git a/src/util/config/ConfigDefinition.hpp b/src/util/config/ConfigDefinition.hpp index f59164b3f..debba4480 100644 --- a/src/util/config/ConfigDefinition.hpp +++ b/src/util/config/ConfigDefinition.hpp @@ -81,7 +81,7 @@ public: * @return Value of key of type T */ template - T + [[nodiscard]] T get(std::string_view fullKey) const { ASSERT(map_.contains(fullKey), "key {} does not exist in config", fullKey); @@ -164,7 +164,7 @@ public: * @return The value of type T if it exists, std::nullopt otherwise. */ template - std::optional + [[nodiscard]] std::optional maybeValue(std::string_view fullKey) const { return getValueView(fullKey).asOptional(); diff --git a/src/util/config/ConfigFileInterface.hpp b/src/util/config/ConfigFileInterface.hpp index 898d8f6c5..3b8897bb9 100644 --- a/src/util/config/ConfigFileInterface.hpp +++ b/src/util/config/ConfigFileInterface.hpp @@ -25,7 +25,7 @@ public: * @param key The key of configuration. * @return the value associated with key. */ - virtual Value + [[nodiscard]] virtual Value getValue(std::string_view key) const = 0; /** @@ -34,7 +34,7 @@ public: * @param key The key of the configuration array. * @return A vector of configuration values some of which could be nullopt */ - virtual std::vector> + [[nodiscard]] virtual std::vector> getArray(std::string_view key) const = 0; /** @@ -43,7 +43,7 @@ public: * @param key The key to search for. * @return true if key exists in configuration file, false otherwise. */ - virtual bool + [[nodiscard]] virtual bool containsKey(std::string_view key) const = 0; /** @@ -51,7 +51,7 @@ public: * * @return A vector of all keys in the configuration file. */ - virtual std::vector + [[nodiscard]] virtual std::vector getAllKeys() const = 0; }; diff --git a/src/util/config/ConfigValue.hpp b/src/util/config/ConfigValue.hpp index 2423e2621..f87a86d94 100644 --- a/src/util/config/ConfigValue.hpp +++ b/src/util/config/ConfigValue.hpp @@ -101,8 +101,8 @@ public: ASSERT(cons_.has_value(), "Constraint must be defined"); if (value_.has_value()) { - auto const& temp = cons_.value().get(); - auto const& result = temp.checkConstraint(value_.value()); + auto const& temp = cons_->get(); + auto const& result = temp.checkConstraint(*value_); if (result.has_value()) { // useful for specifying clear Error message std::string type; @@ -113,7 +113,7 @@ public: [&type](double tmp) { type = fmt::format("double {}", tmp); }, [&type](int64_t tmp) { type = fmt::format("int {}", tmp); }, }, - value_.value() + *value_ ); ASSERT(false, "Value {} ConfigValue does not satisfy the set Constraint", type); } @@ -185,7 +185,7 @@ public: getValue() const { ASSERT(value_.has_value(), "getValue() is called when there is no value set"); - return value_.value(); + return *value_; // NOLINT(bugprone-unchecked-optional-access) } /** @@ -202,7 +202,7 @@ public: stream << "- **Type**: " << val.type() << "\n"; if (val.description_.has_value()) { stream << "- **Default value**: " << *val.description_ << "\n"; - } else if (val.hasValue()) { + } else if (val.value_.has_value()) { stream << "- **Default value**: `" << *val.value_ << "`\n"; } else { stream << "- **Default value**: None\n"; diff --git a/src/util/config/ObjectView.cpp b/src/util/config/ObjectView.cpp index 5efffaa09..65aa62189 100644 --- a/src/util/config/ObjectView.cpp +++ b/src/util/config/ObjectView.cpp @@ -40,7 +40,7 @@ ObjectView::getValueView(std::string_view key) const { auto const fullKey = getFullKey(key); if (arrayIndex_.has_value()) { - return clioConfig_.get().getArray(fullKey).valueAt(arrayIndex_.value()); + return clioConfig_.get().getArray(fullKey).valueAt(*arrayIndex_); } return clioConfig_.get().getValueView(fullKey); } @@ -53,7 +53,7 @@ ObjectView::getObject(std::string_view key) const return clioConfig_.get().getObject(fullKey); } if (startsWithKey(fullKey) && arrayIndex_.has_value()) { - return ObjectView(fullKey, arrayIndex_.value(), clioConfig_); + return ObjectView(fullKey, *arrayIndex_, clioConfig_); } ASSERT(false, "Key {} does not exist in object", fullKey); std::unreachable(); diff --git a/src/util/config/ObjectView.hpp b/src/util/config/ObjectView.hpp index 9284e2503..09efa9efa 100644 --- a/src/util/config/ObjectView.hpp +++ b/src/util/config/ObjectView.hpp @@ -67,7 +67,7 @@ public: * @return Value of key of type T */ template - T + [[nodiscard]] T get(std::string_view key) const { return getValueView(key).getValueImpl(); @@ -81,7 +81,7 @@ public: * @return The value of type T if it exists, std::nullopt otherwise. */ template - std::optional + [[nodiscard]] std::optional maybeValue(std::string_view key) const { return getValueView(key).asOptional(); diff --git a/src/util/config/ValueView.hpp b/src/util/config/ValueView.hpp index fcec1f4dc..ca8e6df4b 100644 --- a/src/util/config/ValueView.hpp +++ b/src/util/config/ValueView.hpp @@ -142,7 +142,7 @@ public: * @return The value cast to the specified type T */ template - T + [[nodiscard]] T getValueImpl() const { ASSERT(configVal_.get().hasValue(), "ConfigValue does not have a value"); @@ -173,7 +173,7 @@ public: * @return Returns the value as an optional value exists, or std::nullopt if not */ template - std::optional + [[nodiscard]] std::optional asOptional() const { ASSERT(isOptional(), "A Config Value is not an optional value"); diff --git a/src/util/log/Logger.cpp b/src/util/log/Logger.cpp index 4327d469c..2634fd478 100644 --- a/src/util/log/Logger.cpp +++ b/src/util/log/Logger.cpp @@ -132,7 +132,7 @@ public: } } - std::unique_ptr + [[nodiscard]] std::unique_ptr clone() const override { return std::make_unique(wrapped_formatter_->clone()); @@ -334,7 +334,7 @@ LogService::getSinks(config::ClioConfigDefinition const& config) createConsoleSinks(config.get("log.enable_console"), format); if (auto const logDir = config.maybeValue("log.directory"); logDir.has_value()) { - std::filesystem::path const dirPath{logDir.value()}; + std::filesystem::path const dirPath{*logDir}; if (not std::filesystem::exists(dirPath)) { if (std::error_code error; not std::filesystem::create_directories(dirPath, error)) { return std::unexpected{fmt::format( @@ -352,7 +352,7 @@ LogService::getSinks(config::ClioConfigDefinition const& config) } FileLoggingParams const params{ - .logDir = logDir.value(), + .logDir = *logDir, .rotation = rotation, }; allSinks.push_back(createFileSink(params, format)); diff --git a/src/util/prometheus/Counter.hpp b/src/util/prometheus/Counter.hpp index 9f43a5a04..e6ee8e7fb 100644 --- a/src/util/prometheus/Counter.hpp +++ b/src/util/prometheus/Counter.hpp @@ -90,7 +90,7 @@ struct AnyCounter : MetricBase, impl::AnyCounterBase { * * @return The value */ - ValueType + [[nodiscard]] ValueType value() const { return this->pimpl_->value(); diff --git a/src/util/prometheus/Gauge.hpp b/src/util/prometheus/Gauge.hpp index aaba31861..8c36c6510 100644 --- a/src/util/prometheus/Gauge.hpp +++ b/src/util/prometheus/Gauge.hpp @@ -103,7 +103,7 @@ struct AnyGauge : MetricBase, impl::AnyCounterBase { * * @return The value of the counter */ - ValueType + [[nodiscard]] ValueType value() const { return this->pimpl_->value(); diff --git a/src/util/prometheus/Label.hpp b/src/util/prometheus/Label.hpp index 40f358b74..0ccbfe1c7 100644 --- a/src/util/prometheus/Label.hpp +++ b/src/util/prometheus/Label.hpp @@ -27,7 +27,7 @@ public: * * @return The serialized label */ - std::string + [[nodiscard]] std::string serialize() const; private: @@ -55,7 +55,7 @@ public: * * @return The serialized labels */ - std::string + [[nodiscard]] std::string serialize() const; private: diff --git a/src/util/prometheus/MetricBase.hpp b/src/util/prometheus/MetricBase.hpp index 7d60cf7ce..5266ffccb 100644 --- a/src/util/prometheus/MetricBase.hpp +++ b/src/util/prometheus/MetricBase.hpp @@ -41,14 +41,14 @@ public: * @brief Get the name of the metric * @return The name of the metric */ - std::string const& + [[nodiscard]] std::string const& name() const; /** * @brief Get the labels of the metric in serialized format, e.g. {name="value",name2="value2"} * @return The labels of the metric */ - std::string const& + [[nodiscard]] std::string const& labelsString() const; protected: diff --git a/src/util/prometheus/MetricsFamily.hpp b/src/util/prometheus/MetricsFamily.hpp index e7a299e2e..6d26652fb 100644 --- a/src/util/prometheus/MetricsFamily.hpp +++ b/src/util/prometheus/MetricsFamily.hpp @@ -82,7 +82,7 @@ public: * * @return The name */ - std::string const& + [[nodiscard]] std::string const& name() const; /** @@ -90,7 +90,7 @@ public: * * @return The description */ - MetricType + [[nodiscard]] MetricType type() const; private: diff --git a/src/util/prometheus/Prometheus.hpp b/src/util/prometheus/Prometheus.hpp index 802e83b98..8d27fa59c 100644 --- a/src/util/prometheus/Prometheus.hpp +++ b/src/util/prometheus/Prometheus.hpp @@ -160,7 +160,7 @@ public: * * @return true if prometheus is enabled */ - bool + [[nodiscard]] bool isEnabled() const { return isEnabled_; @@ -171,7 +171,7 @@ public: * * @return true if the reply should be compressed */ - bool + [[nodiscard]] bool compressReplyEnabled() const { return compressReplyEnabled_; diff --git a/src/util/prometheus/impl/AnyCounterBase.hpp b/src/util/prometheus/impl/AnyCounterBase.hpp index aafeaa2bf..f29a429e1 100644 --- a/src/util/prometheus/impl/AnyCounterBase.hpp +++ b/src/util/prometheus/impl/AnyCounterBase.hpp @@ -29,7 +29,7 @@ protected: virtual void set(ValueType) = 0; - virtual ValueType + [[nodiscard]] virtual ValueType value() const = 0; }; @@ -53,7 +53,7 @@ protected: impl.set(v); } - ValueType + [[nodiscard]] ValueType value() const override { return impl.value(); diff --git a/src/util/prometheus/impl/CounterImpl.hpp b/src/util/prometheus/impl/CounterImpl.hpp index 34e3b34bc..b5a94cc43 100644 --- a/src/util/prometheus/impl/CounterImpl.hpp +++ b/src/util/prometheus/impl/CounterImpl.hpp @@ -43,7 +43,7 @@ public: value_->set(value); } - ValueType + [[nodiscard]] ValueType value() const { return value_->value(); diff --git a/src/util/requests/Types.cpp b/src/util/requests/Types.cpp index 602719728..067543003 100644 --- a/src/util/requests/Types.cpp +++ b/src/util/requests/Types.cpp @@ -20,7 +20,7 @@ RequestError::RequestError(std::string message, boost::beast::error_code errorCo { message_.append(": "); if (auto const sslError = impl::sslErrorToString(errorCode); sslError.has_value()) { - message_.append(sslError.value()); + message_.append(*sslError); } else { message_.append(errorCode.message()); } diff --git a/src/util/requests/Types.hpp b/src/util/requests/Types.hpp index 8166af068..eaef87343 100644 --- a/src/util/requests/Types.hpp +++ b/src/util/requests/Types.hpp @@ -35,13 +35,13 @@ public: /** * @return The error message */ - std::string const& + [[nodiscard]] std::string const& message() const; /** * @return The error code, if any */ - std::optional const& + [[nodiscard]] std::optional const& errorCode() const; }; diff --git a/src/util/requests/WsConnection.hpp b/src/util/requests/WsConnection.hpp index 6c9e6a626..709bd024f 100644 --- a/src/util/requests/WsConnection.hpp +++ b/src/util/requests/WsConnection.hpp @@ -150,7 +150,7 @@ public: * @param yield yield context * @return WebSocket connection or error */ - std::expected + [[nodiscard]] std::expected sslConnect(boost::asio::yield_context yield) const; /** @@ -159,7 +159,7 @@ public: * @param yield yield context * @return WebSocket connection or error */ - std::expected + [[nodiscard]] std::expected plainConnect(boost::asio::yield_context yield) const; /** @@ -168,7 +168,7 @@ public: * @param yield yield context * @return WebSocket connection or error */ - std::expected + [[nodiscard]] std::expected connect(boost::asio::yield_context yield) const; static constexpr std::chrono::seconds kDEFAULT_TIMEOUT{ diff --git a/src/web/AdminVerificationStrategy.hpp b/src/web/AdminVerificationStrategy.hpp index bc7c28abf..d32ee3639 100644 --- a/src/web/AdminVerificationStrategy.hpp +++ b/src/web/AdminVerificationStrategy.hpp @@ -29,7 +29,7 @@ public: * @param ip The ip addr of the client * @return true if authorized; false otherwise */ - virtual bool + [[nodiscard]] virtual bool isAdmin(RequestHeader const& request, std::string_view ip) const = 0; }; @@ -45,7 +45,7 @@ public: * @param ip The ip addr of the client * @return true if authorized; false otherwise */ - bool + [[nodiscard]] bool isAdmin(RequestHeader const&, std::string_view ip) const override; }; @@ -76,7 +76,7 @@ public: * @param request The request from a host * @return true if the password from request matches admin password from config */ - bool + [[nodiscard]] bool isAdmin(RequestHeader const& request, std::string_view) const override; }; diff --git a/src/web/ProxyIpResolver.hpp b/src/web/ProxyIpResolver.hpp index b5dc014af..016e782ea 100644 --- a/src/web/ProxyIpResolver.hpp +++ b/src/web/ProxyIpResolver.hpp @@ -66,7 +66,7 @@ public: * @return The resolved client IP address if the connection is from a trusted proxy, otherwise * std::nullopt. */ - std::optional + [[nodiscard]] std::optional resolveClientIp(std::string const& connectionIp, HttpHeaders const& headers) const; /** diff --git a/src/web/RPCServerHandler.hpp b/src/web/RPCServerHandler.hpp index 86ca72c91..f4c1520e2 100644 --- a/src/web/RPCServerHandler.hpp +++ b/src/web/RPCServerHandler.hpp @@ -257,10 +257,10 @@ private: } boost::json::array warnings = std::move(result.warnings); - warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcClio)); + warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcClio)); if (etl_->lastCloseAgeSeconds() >= 60) - warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcOutdated)); + warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcOutdated)); response["warnings"] = warnings; connection->send(boost::json::serialize(response)); @@ -277,7 +277,7 @@ private: } } - bool + [[nodiscard]] bool shouldReplaceParams(boost::json::object const& req) const { auto const hasParams = req.contains(JS(params)); diff --git a/src/web/Server.hpp b/src/web/Server.hpp index a79299996..a41b996af 100644 --- a/src/web/Server.hpp +++ b/src/web/Server.hpp @@ -338,7 +338,7 @@ private: if (!ec) { auto ctxRef = ctx_ - ? std::optional>{ctx_.value()} + ? std::optional>{*ctx_} : std::nullopt; std::make_shared>( diff --git a/src/web/SubscriptionContextInterface.hpp b/src/web/SubscriptionContextInterface.hpp index 712a553f7..da168b23d 100644 --- a/src/web/SubscriptionContextInterface.hpp +++ b/src/web/SubscriptionContextInterface.hpp @@ -54,7 +54,7 @@ public: * * @return The API subversion. */ - virtual uint32_t + [[nodiscard]] virtual uint32_t apiSubversion() const = 0; }; diff --git a/src/web/dosguard/Weights.hpp b/src/web/dosguard/Weights.hpp index 557ae21c7..722e6f5d9 100644 --- a/src/web/dosguard/Weights.hpp +++ b/src/web/dosguard/Weights.hpp @@ -63,7 +63,7 @@ public: * @param request Json request * @return size_t The weight value (specific weight if defined, otherwise default weight) */ - size_t + [[nodiscard]] size_t requestWeight(boost::json::object const& request) const override; }; diff --git a/src/web/dosguard/WeightsInterface.hpp b/src/web/dosguard/WeightsInterface.hpp index 782735566..9f43573de 100644 --- a/src/web/dosguard/WeightsInterface.hpp +++ b/src/web/dosguard/WeightsInterface.hpp @@ -22,7 +22,7 @@ public: * @param request The JSON object representing the request * @return The calculated weight of the request */ - virtual size_t + [[nodiscard]] virtual size_t requestWeight(boost::json::object const& request) const = 0; }; diff --git a/src/web/dosguard/WhitelistHandler.hpp b/src/web/dosguard/WhitelistHandler.hpp index 83b7b342f..7823cf927 100644 --- a/src/web/dosguard/WhitelistHandler.hpp +++ b/src/web/dosguard/WhitelistHandler.hpp @@ -47,7 +47,7 @@ public: * @param ip IP address * @return true if the given IP is whitelisted; false otherwise */ - bool + [[nodiscard]] bool isWhiteListed(std::string_view ip) const; private: @@ -115,7 +115,7 @@ public: * @param ip The IP to check * @return true if the given IP is whitelisted; false otherwise */ - bool + [[nodiscard]] bool isWhiteListed(std::string_view ip) const override { return whitelist_.isWhiteListed(ip); diff --git a/src/web/impl/ErrorHandling.hpp b/src/web/impl/ErrorHandling.hpp index 7edd6c230..ad08ddea1 100644 --- a/src/web/impl/ErrorHandling.hpp +++ b/src/web/impl/ErrorHandling.hpp @@ -147,7 +147,7 @@ public: } } - boost::json::object + [[nodiscard]] boost::json::object composeError(auto const& error) const { auto e = rpc::makeError(error); @@ -163,7 +163,7 @@ public: if (connection_->upgraded) appendFieldIfExist(JS(api_version)); - e[JS(request)] = request_.value(); + e[JS(request)] = *request_; } if (connection_->upgraded) { diff --git a/src/web/impl/HttpBase.hpp b/src/web/impl/HttpBase.hpp index 04c128325..41927c12f 100644 --- a/src/web/impl/HttpBase.hpp +++ b/src/web/impl/HttpBase.hpp @@ -323,11 +323,11 @@ public: jsonResponse["warning"] = "load"; if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) { jsonResponse["warnings"].as_array().push_back( - rpc::makeWarning(rpc::WarnRpcRateLimit) + rpc::makeWarning(rpc::WarningCode::WarnRpcRateLimit) ); } else { jsonResponse["warnings"] = - boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)}; + boost::json::array{rpc::makeWarning(rpc::WarningCode::WarnRpcRateLimit)}; } // Reserialize when we need to include this warning @@ -361,7 +361,7 @@ public: } private: - http::response + [[nodiscard]] http::response httpResponse(http::status status, std::string contentType, std::string message) const { http::response res{status, req_.version()}; diff --git a/src/web/impl/WsBase.hpp b/src/web/impl/WsBase.hpp index c0c7449a5..c2ff0aac4 100644 --- a/src/web/impl/WsBase.hpp +++ b/src/web/impl/WsBase.hpp @@ -210,11 +210,11 @@ public: if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) { jsonResponse["warnings"].as_array().push_back( - rpc::makeWarning(rpc::WarnRpcRateLimit) + rpc::makeWarning(rpc::WarningCode::WarnRpcRateLimit) ); } else { jsonResponse["warnings"] = - boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)}; + boost::json::array{rpc::makeWarning(rpc::WarningCode::WarnRpcRateLimit)}; } // Reserialize when we need to include this warning diff --git a/src/web/ng/Connection.hpp b/src/web/ng/Connection.hpp index 67f3066c2..f11abb50b 100644 --- a/src/web/ng/Connection.hpp +++ b/src/web/ng/Connection.hpp @@ -42,7 +42,7 @@ public: * * @return true if the connection was upgraded. */ - virtual bool + [[nodiscard]] virtual bool wasUpgraded() const = 0; /** @@ -50,7 +50,7 @@ public: * * @return The ip of the client. */ - std::string const& + [[nodiscard]] std::string const& ip() const; /** @@ -89,7 +89,7 @@ public: * * @return true if the client is an admin. */ - bool + [[nodiscard]] bool isAdmin() const; /** diff --git a/src/web/ng/RPCServerHandler.hpp b/src/web/ng/RPCServerHandler.hpp index 1348f3175..0eeb3ea32 100644 --- a/src/web/ng/RPCServerHandler.hpp +++ b/src/web/ng/RPCServerHandler.hpp @@ -115,7 +115,7 @@ public: [this, &request, &response, - &onTaskComplete = onTaskComplete.value(), + &onTaskComplete = *onTaskComplete, // NOLINT(bugprone-unchecked-optional-access) &connectionMetadata, subscriptionContext = std::move(subscriptionContext)](boost::asio::yield_context innerYield) mutable { @@ -171,7 +171,7 @@ public: if (not postSuccessful) { // onTaskComplete must be called to notify coroutineGroup that the foreign task is done - onTaskComplete->operator()(); + (*onTaskComplete)(); // NOLINT(bugprone-unchecked-optional-access) rpcEngine_->notifyTooBusy(); return impl::ErrorHelper{request}.makeTooBusyError(); } @@ -180,11 +180,13 @@ public: coroutineGroup.asyncWait(yield); ASSERT(response.has_value(), "Woke up coroutine without setting response"); + // NOLINTBEGIN(bugprone-unchecked-optional-access) if (not dosguard_.get().add(connectionMetadata.ip(), response->message().size())) { response->setMessage(makeLoadWarning(*response)); } - return std::move(response).value(); + return *std::move(response); + // NOLINTEND(bugprone-unchecked-optional-access) } private: @@ -317,10 +319,10 @@ private: } boost::json::array warnings = std::move(result.warnings); - warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcClio)); + warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcClio)); if (etl_->lastCloseAgeSeconds() >= 60) - warnings.emplace_back(rpc::makeWarning(rpc::WarnRpcOutdated)); + warnings.emplace_back(rpc::makeWarning(rpc::WarningCode::WarnRpcOutdated)); response["warnings"] = warnings; return Response{boost::beast::http::status::ok, response, rawRequest}; @@ -361,14 +363,17 @@ private: auto jsonResponse = boost::json::parse(response.message()).as_object(); jsonResponse["warning"] = "load"; if (jsonResponse.contains("warnings") && jsonResponse["warnings"].is_array()) { - jsonResponse["warnings"].as_array().push_back(rpc::makeWarning(rpc::WarnRpcRateLimit)); + jsonResponse["warnings"].as_array().push_back( + rpc::makeWarning(rpc::WarningCode::WarnRpcRateLimit) + ); } else { - jsonResponse["warnings"] = boost::json::array{rpc::makeWarning(rpc::WarnRpcRateLimit)}; + jsonResponse["warnings"] = + boost::json::array{rpc::makeWarning(rpc::WarningCode::WarnRpcRateLimit)}; } return jsonResponse; } - bool + [[nodiscard]] bool shouldReplaceParams(boost::json::object const& req) const { auto const hasParams = req.contains(JS(params)); diff --git a/src/web/ng/Request.hpp b/src/web/ng/Request.hpp index 04be86e7d..ca626776a 100644 --- a/src/web/ng/Request.hpp +++ b/src/web/ng/Request.hpp @@ -59,7 +59,7 @@ public: * * @return The method of the request. */ - Method + [[nodiscard]] Method method() const; /** @@ -67,7 +67,7 @@ public: * * @return true if the request is an HTTP request, false otherwise. */ - bool + [[nodiscard]] bool isHttp() const; /** @@ -75,7 +75,7 @@ public: * * @return The HTTP request or std::nullopt if the request is a WebSocket request. */ - std::optional< + [[nodiscard]] std::optional< std::reference_wrapper const>> asHttpRequest() const; @@ -85,7 +85,7 @@ public: * * @return The message of the request. */ - std::string_view + [[nodiscard]] std::string_view message() const; /** @@ -93,7 +93,7 @@ public: * * @return The target of the request or std::nullopt if the request is a WebSocket request. */ - std::optional + [[nodiscard]] std::optional target() const; /** @@ -101,7 +101,7 @@ public: * * @return The headers of the request. */ - HttpHeaders const& + [[nodiscard]] HttpHeaders const& httpHeaders() const; /** @@ -110,7 +110,7 @@ public: * @param headerName The name of the header. * @return The value of the header or std::nullopt if the header does not exist. */ - std::optional + [[nodiscard]] std::optional headerValue(boost::beast::http::field headerName) const; /** @@ -119,7 +119,7 @@ public: * @param headerName The name of the header. * @return The value of the header or std::nullopt if the header does not exist. */ - std::optional + [[nodiscard]] std::optional headerValue(std::string const& headerName) const; private: @@ -130,7 +130,7 @@ private: * * @return The HTTP request. */ - HttpRequest const& + [[nodiscard]] HttpRequest const& httpRequest() const; }; diff --git a/src/web/ng/Response.cpp b/src/web/ng/Response.cpp index f72bb5190..c91455837 100644 --- a/src/web/ng/Response.cpp +++ b/src/web/ng/Response.cpp @@ -73,7 +73,8 @@ makeData(http::status status, MessageType message, Request const& request) if (not request.isHttp()) return std::move(messageData).body; - auto const& httpRequest = request.asHttpRequest()->get(); + auto const& httpRequest = + (*request.asHttpRequest()).get(); // NOLINT(bugprone-unchecked-optional-access) return makeHttpData( std::move(messageData), status, httpRequest.version(), httpRequest.keep_alive() ); @@ -131,7 +132,8 @@ Response::Response( ) { ASSERT(request.isHttp(), "Request must be HTTP to construct response from HTTP response"); - data = prepareResponse(std::move(response), request.asHttpRequest()->get().keep_alive()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + data = prepareResponse(std::move(response), (*request.asHttpRequest()).get().keep_alive()); } std::string const& diff --git a/src/web/ng/Response.hpp b/src/web/ng/Response.hpp index c165ff608..f21b9882d 100644 --- a/src/web/ng/Response.hpp +++ b/src/web/ng/Response.hpp @@ -87,7 +87,7 @@ public: * * @return The message of the response. */ - std::string const& + [[nodiscard]] std::string const& message() const; /** @@ -121,7 +121,7 @@ public: * * @return The message of the response as a const buffer. */ - boost::asio::const_buffer + [[nodiscard]] boost::asio::const_buffer asWsResponse() const&; }; diff --git a/src/web/ng/Server.cpp b/src/web/ng/Server.cpp index c94efa846..85d162e39 100644 --- a/src/web/ng/Server.cpp +++ b/src/web/ng/Server.cpp @@ -300,7 +300,9 @@ Server::handleConnection(boost::asio::ip::tcp::socket socket, boost::asio::yield ); if (not connectionExpected.has_value()) { if (connectionExpected.error().has_value()) { - LOG(log_.info()) << *connectionExpected.error(); + LOG( + log_.info() + ) << *connectionExpected.error(); // NOLINT(bugprone-unchecked-optional-access) } return; } diff --git a/src/web/ng/impl/ConnectionHandler.cpp b/src/web/ng/impl/ConnectionHandler.cpp index 9ac7ed056..61f9d3ccc 100644 --- a/src/web/ng/impl/ConnectionHandler.cpp +++ b/src/web/ng/impl/ConnectionHandler.cpp @@ -43,7 +43,7 @@ handleHttpRequest( ) { ASSERT(request.target().has_value(), "Got not a HTTP request"); - auto it = handlers.find(*request.target()); + auto it = handlers.find(*request.target()); // NOLINT(bugprone-unchecked-optional-access) if (it == handlers.end()) { return Response{boost::beast::http::status::bad_request, "Bad target", request}; } @@ -282,7 +282,7 @@ ConnectionHandler::sequentRequestResponseLoop( auto maybeReturnValue = processRequest(connection, subscriptionContext, *expectedRequest, yield); if (maybeReturnValue.has_value()) - return maybeReturnValue.value(); + return *maybeReturnValue; } } @@ -326,7 +326,7 @@ ConnectionHandler::parallelRequestResponseLoop( processRequest(connection, subscriptionContext, request, innerYield); if (maybeCloseConnectionGracefully.has_value()) { stop = true; - closeConnectionGracefully &= maybeCloseConnectionGracefully.value(); + closeConnectionGracefully &= *maybeCloseConnectionGracefully; } } ); diff --git a/src/web/ng/impl/ConnectionHandler.hpp b/src/web/ng/impl/ConnectionHandler.hpp index 1167060c5..203ca835d 100644 --- a/src/web/ng/impl/ConnectionHandler.hpp +++ b/src/web/ng/impl/ConnectionHandler.hpp @@ -101,7 +101,7 @@ public: void stop(boost::asio::yield_context yield); - bool + [[nodiscard]] bool isStopping() const; private: @@ -112,7 +112,7 @@ private: * @param connection The connection that caused the error. * @return True if the connection should be gracefully closed, false otherwise. */ - bool + [[nodiscard]] bool handleError(Error const& error, Connection const& connection) const; /** diff --git a/src/web/ng/impl/ErrorHandling.cpp b/src/web/ng/impl/ErrorHandling.cpp index fed551b18..4b46ccb2a 100644 --- a/src/web/ng/impl/ErrorHandling.cpp +++ b/src/web/ng/impl/ErrorHandling.cpp @@ -42,7 +42,7 @@ composeErrorImpl( if (not rawRequest.isHttp()) appendFieldIfExist(JS(api_version)); - e[JS(request)] = request.value(); + e[JS(request)] = *request; } if (not rawRequest.isHttp()) { diff --git a/src/web/ng/impl/HttpConnection.hpp b/src/web/ng/impl/HttpConnection.hpp index b41f4a36b..3f397cf15 100644 --- a/src/web/ng/impl/HttpConnection.hpp +++ b/src/web/ng/impl/HttpConnection.hpp @@ -124,7 +124,7 @@ public: return {}; } - bool + [[nodiscard]] bool wasUpgraded() const override { return false; @@ -156,7 +156,7 @@ public: receive(boost::asio::yield_context yield) override { if (request_.has_value()) { - Request result{std::move(request_).value()}; + Request result{*std::move(request_)}; request_.reset(); return result; } @@ -196,7 +196,7 @@ public: request_ = std::move(expectedRequest).value(); - return boost::beast::websocket::is_upgrade(request_.value()); + return boost::beast::websocket::is_upgrade(*request_); } std::expected @@ -211,7 +211,7 @@ public: std::move(stream_), std::move(ip_), std::move(buffer_), - std::move(request_).value(), + std::move(*request_), // NOLINT(bugprone-unchecked-optional-access) tagDecoratorFactory, yield ); diff --git a/src/web/ng/impl/WsConnection.hpp b/src/web/ng/impl/WsConnection.hpp index 084c52d19..3e28183ba 100644 --- a/src/web/ng/impl/WsConnection.hpp +++ b/src/web/ng/impl/WsConnection.hpp @@ -99,7 +99,7 @@ public: return {}; } - bool + [[nodiscard]] bool wasUpgraded() const override { return true; diff --git a/tests/common/data/cassandra/FakesAndMocks.hpp b/tests/common/data/cassandra/FakesAndMocks.hpp index a98c29611..4e805751d 100644 --- a/tests/common/data/cassandra/FakesAndMocks.hpp +++ b/tests/common/data/cassandra/FakesAndMocks.hpp @@ -23,7 +23,7 @@ struct FakeResultOrError { return err.code() == CASS_OK; } - CassandraError + [[nodiscard]] CassandraError error() const { return err; @@ -45,7 +45,7 @@ struct FakePreparedStatement {}; struct FakeFuture { FakeResultOrError data; - FakeResultOrError + [[nodiscard]] FakeResultOrError get() const { return data; diff --git a/tests/common/util/AsioContextTestFixture.hpp b/tests/common/util/AsioContextTestFixture.hpp index 803d1728d..381972cdb 100644 --- a/tests/common/util/AsioContextTestFixture.hpp +++ b/tests/common/util/AsioContextTestFixture.hpp @@ -33,7 +33,7 @@ struct AsyncAsioContextTest : virtual public ::testing::Test { ~AsyncAsioContextTest() override { work_.reset(); - if (runner_->joinable()) + if (runner_.has_value() && runner_->joinable()) runner_->join(); ctx_.stop(); } @@ -42,7 +42,7 @@ struct AsyncAsioContextTest : virtual public ::testing::Test { stop() { work_.reset(); - if (runner_->joinable()) + if (runner_.has_value() && runner_->joinable()) runner_->join(); ctx_.stop(); } diff --git a/tests/common/util/BinaryTestObject.cpp b/tests/common/util/BinaryTestObject.cpp index 4f53bb897..63913ce65 100644 --- a/tests/common/util/BinaryTestObject.cpp +++ b/tests/common/util/BinaryTestObject.cpp @@ -91,8 +91,9 @@ createObject(etl::model::Object::ModType modType, std::string key) return { .key = binaryStringToUint256(hexStringToBinaryString(key)), .keyRaw = hexStringToBinaryString(key), - .data = modType == etl::model::Object::ModType::Deleted ? ripple::Blob{} - : *ripple::strUnHex(kOBJ_BLOB), + .data = modType == etl::model::Object::ModType::Deleted + ? ripple::Blob{} + : *ripple::strUnHex(kOBJ_BLOB), // NOLINT(bugprone-unchecked-optional-access) .dataRaw = modType == etl::model::Object::ModType::Deleted ? "" : hexStringToBinaryString(kOBJ_BLOB), @@ -120,8 +121,9 @@ createObjectWithBookBase(etl::model::Object::ModType modType, std::string key) return { .key = binaryStringToUint256(hexStringToBinaryString(key)), .keyRaw = hexStringToBinaryString(key), - .data = modType == etl::model::Object::ModType::Deleted ? ripple::Blob{} - : *ripple::strUnHex(kOBJ_BLOB), + .data = modType == etl::model::Object::ModType::Deleted + ? ripple::Blob{} + : *ripple::strUnHex(kOBJ_BLOB), // NOLINT(bugprone-unchecked-optional-access) .dataRaw = modType == etl::model::Object::ModType::Deleted ? "" : hexStringToBinaryString(kOBJ_BLOB), diff --git a/tests/common/util/FakeFetchResponse.hpp b/tests/common/util/FakeFetchResponse.hpp index 67f561df2..480c23d1a 100644 --- a/tests/common/util/FakeFetchResponse.hpp +++ b/tests/common/util/FakeFetchResponse.hpp @@ -20,7 +20,7 @@ public: return &first_; } - std::string + [[nodiscard]] std::string book_base() const { return base_; @@ -52,23 +52,23 @@ public: class FakeLedgerObject { public: - enum ModType : int { MODIFIED, DELETED }; + enum class ModType : int { MODIFIED, DELETED }; private: std::string key_; std::string data_; std::string predecessor_; std::string successor_; - ModType mod_ = MODIFIED; + ModType mod_ = ModType::MODIFIED; public: - ModType + [[nodiscard]] ModType mod_type() const { return mod_; } - std::string + [[nodiscard]] std::string key() const { return key_; @@ -80,7 +80,7 @@ public: return &key_; } - std::string + [[nodiscard]] std::string data() const { return data_; @@ -120,7 +120,7 @@ class FakeTransactionsList { std::size_t size_ = 0; public: - std::size_t + [[nodiscard]] std::size_t transactions_size() const { return size_; @@ -131,7 +131,7 @@ class FakeObjectsList { std::size_t size_ = 0; public: - std::size_t + [[nodiscard]] std::size_t objects_size() const { return size_; @@ -173,7 +173,7 @@ struct FakeFetchResponse { return {}; } - bool + [[nodiscard]] bool object_neighbors_included() const { return objectNeighborsIncluded; @@ -185,7 +185,7 @@ struct FakeFetchResponse { return &ledgerObjects; } - std::string + [[nodiscard]] std::string ledger_header() const { return ledgerHeader; diff --git a/tests/common/util/MockSource.hpp b/tests/common/util/MockSource.hpp index c5e815601..fbc4c4bbc 100644 --- a/tests/common/util/MockSource.hpp +++ b/tests/common/util/MockSource.hpp @@ -86,7 +86,7 @@ public: mock_->stop(yield); } - bool + [[nodiscard]] bool isConnected() const override { return mock_->isConnected(); @@ -98,19 +98,19 @@ public: mock_->setForwarding(isForwarding); } - boost::json::object + [[nodiscard]] boost::json::object toJson() const override { return mock_->toJson(); } - std::string + [[nodiscard]] std::string toString() const override { return mock_->toString(); } - bool + [[nodiscard]] bool hasLedger(uint32_t sequence) const override { return mock_->hasLedger(sequence); @@ -132,7 +132,7 @@ public: return mock_->loadInitialLedger(sequence, maxLedger, observer); } - std::expected + [[nodiscard]] std::expected forwardToRippled( boost::json::object const& request, std::optional const& forwardToRippledClientIp, @@ -233,7 +233,7 @@ public: { auto& callbacks = mockData_.at(index).callbacks; [&]() { ASSERT_TRUE(callbacks.has_value()) << "Callbacks not set"; }(); - return *callbacks; + return *callbacks; // NOLINT(bugprone-unchecked-optional-access) } }; diff --git a/tests/common/util/StringUtils.cpp b/tests/common/util/StringUtils.cpp index 5586dde11..c639e011d 100644 --- a/tests/common/util/StringUtils.cpp +++ b/tests/common/util/StringUtils.cpp @@ -14,7 +14,7 @@ hexStringToBinaryString(std::string const& hex) auto const blob = ripple::strUnHex(hex); std::string strBlob; - for (auto c : *blob) + for (auto c : *blob) // NOLINT(bugprone-unchecked-optional-access) strBlob += c; return strBlob; diff --git a/tests/common/util/TestHttpServer.hpp b/tests/common/util/TestHttpServer.hpp index 765c2ad36..2797ae064 100644 --- a/tests/common/util/TestHttpServer.hpp +++ b/tests/common/util/TestHttpServer.hpp @@ -54,7 +54,7 @@ public: * * @return string port number */ - std::string + [[nodiscard]] std::string port() const; private: diff --git a/tests/common/util/TestObject.cpp b/tests/common/util/TestObject.cpp index 71d1f71ad..388963723 100644 --- a/tests/common/util/TestObject.cpp +++ b/tests/common/util/TestObject.cpp @@ -47,7 +47,8 @@ ripple::Slice const kSLICE("test", 4); ripple::AccountID getAccountIdWithString(std::string_view id) { - return util::parseBase58Wrapper(std::string(id)).value(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + return *util::parseBase58Wrapper(std::string(id)); } ripple::uint256 @@ -79,7 +80,7 @@ createLedgerHeader( // Note: be cautious of using age values close to each other as the underlying NetClock // precision is seconds and the small time difference may lead to comparison bugs auto const now = duration_cast(system_clock::now().time_since_epoch()); - auto const closeTime = (now - seconds{age.value()}).count() - kRIPPLE_EPOCH_START; + auto const closeTime = (now - seconds{*age}).count() - kRIPPLE_EPOCH_START; ledgerHeader.closeTime = ripple::NetClock::time_point{seconds{closeTime}}; } @@ -178,11 +179,12 @@ createPaymentTransactionObject( ripple::STObject obj(ripple::sfTransaction); obj.setFieldU16(ripple::sfTransactionType, ripple::ttPAYMENT); auto account = util::parseBase58Wrapper(std::string(accountId1)); - obj.setAccountID(ripple::sfAccount, account.value()); + obj.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) obj.setFieldAmount(ripple::sfAmount, ripple::STAmount(amount, false)); obj.setFieldAmount(ripple::sfFee, ripple::STAmount(fee, false)); auto account2 = util::parseBase58Wrapper(std::string(accountId2)); - obj.setAccountID(ripple::sfDestination, account2.value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + obj.setAccountID(ripple::sfDestination, *account2); obj.setFieldU32(ripple::sfSequence, seq); obj.setFieldVL(ripple::sfSigningPubKey, kSLICE); return obj; @@ -290,14 +292,15 @@ createCreateOfferTransactionObject( ripple::STObject obj(ripple::sfTransaction); obj.setFieldU16(ripple::sfTransactionType, ripple::ttOFFER_CREATE); auto account = util::parseBase58Wrapper(std::string(accountId)); - obj.setAccountID(ripple::sfAccount, account.value()); + obj.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); obj.setFieldAmount(ripple::sfFee, amount); obj.setFieldU32(ripple::sfSequence, seq); // add amount ripple::Issue const issue1( ripple::Currency{currency}, - util::parseBase58Wrapper(std::string(issuer)).value() + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *util::parseBase58Wrapper(std::string(issuer)) ); if (reverse) { obj.setFieldAmount(ripple::sfTakerPays, ripple::STAmount(issue1, takerGets)); @@ -320,12 +323,14 @@ getIssue(std::string_view currency, std::string_view issuerId) if (currency.size() == 3) { return ripple::Issue( ripple::to_currency(std::string(currency)), - util::parseBase58Wrapper(std::string(issuerId)).value() + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *util::parseBase58Wrapper(std::string(issuerId)) ); } return ripple::Issue( ripple::Currency{currency}, - util::parseBase58Wrapper(std::string(issuerId)).value() + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *util::parseBase58Wrapper(std::string(issuerId)) ); } @@ -709,7 +714,7 @@ createMintNftTxWithMetadata( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_MINT); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); // required field for ttNFTOKEN_MINT @@ -772,7 +777,7 @@ createMintNftTxWithMetadataOfCreatedNode( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_MINT); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); // required field for ttNFTOKEN_MINT @@ -829,7 +834,7 @@ createNftModifyTxWithMetadata(std::string_view accountId, std::string_view nftID ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_MODIFY); auto account = ripple::parseBase58(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(10, false); tx.setFieldAmount(ripple::sfFee, amount); tx.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftID}); @@ -979,7 +984,7 @@ createAcceptNftBuyerOfferTxWithMetadata( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_ACCEPT_OFFER); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); tx.setFieldU32(ripple::sfSequence, seq); @@ -996,7 +1001,8 @@ createAcceptNftBuyerOfferTxWithMetadata( ripple::STObject finalFields(ripple::sfFinalFields); finalFields.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); // for buyer offer, the offer owner is the nft's new owner - finalFields.setAccountID(ripple::sfOwner, account.value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + finalFields.setAccountID(ripple::sfOwner, *account); node.emplace_back(std::move(finalFields)); node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{offerId}); @@ -1026,7 +1032,7 @@ createAcceptNftSellerOfferTxWithMetadata( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_ACCEPT_OFFER); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); tx.setFieldU32(ripple::sfSequence, seq); @@ -1044,7 +1050,8 @@ createAcceptNftSellerOfferTxWithMetadata( finalFields.setFieldH256(ripple::sfNFTokenID, ripple::uint256{nftId}); // offer owner is not the nft's new owner for seller offer, we need to create other nodes for // processing new owner - finalFields.setAccountID(ripple::sfOwner, account.value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + finalFields.setAccountID(ripple::sfOwner, *account); node.emplace_back(finalFields); node.setFieldH256(ripple::sfLedgerIndex, ripple::uint256{offerId}); @@ -1116,7 +1123,7 @@ createCancelNftOffersTxWithMetadata( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_CANCEL_OFFER); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); tx.setFieldU32(ripple::sfSequence, seq); @@ -1168,7 +1175,7 @@ createCreateNftOfferTxWithMetadata( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttNFTOKEN_CREATE_OFFER); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); auto price = ripple::STAmount(offerPrice, false); @@ -1214,7 +1221,7 @@ createOracleSetTxWithMetadata( ripple::STObject tx(ripple::sfTransaction); tx.setFieldU16(ripple::sfTransactionType, ripple::ttORACLE_SET); auto account = util::parseBase58Wrapper(std::string(accountId)); - tx.setAccountID(ripple::sfAccount, account.value()); + tx.setAccountID(ripple::sfAccount, *account); // NOLINT(bugprone-unchecked-optional-access) auto amount = ripple::STAmount(fee, false); tx.setFieldAmount(ripple::sfFee, amount); tx.setFieldU32(ripple::sfLastUpdateTime, lastUpdateTime); @@ -1295,7 +1302,8 @@ createAmmObject( ); ripple::Issue const issue1( ripple::Currency{lpTokenBalanceIssueCurrency}, - util::parseBase58Wrapper(std::string(accountId)).value() + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *util::parseBase58Wrapper(std::string(accountId)) ); amm.setFieldAmount( ripple::sfLPTokenBalance, ripple::STAmount(issue1, lpTokenBalanceIssueAmount) @@ -1783,7 +1791,7 @@ createCredentialObject( credObj.setAccountID(ripple::sfSubject, getAccountIdWithString(acc1)); credObj.setAccountID(ripple::sfIssuer, getAccountIdWithString(acc2)); if (expiration.has_value()) - credObj.setFieldU32(ripple::sfExpiration, expiration.value()); + credObj.setFieldU32(ripple::sfExpiration, *expiration); if (accept) { credObj.setFieldU32(ripple::sfFlags, ripple::lsfAccepted); @@ -1809,7 +1817,9 @@ createAuthCredentialArray( auto credential = ripple::STObject::makeInnerObject(ripple::sfCredential); credential.setAccountID(ripple::sfIssuer, getAccountIdWithString(issuer[i])); credential.setFieldVL( - ripple::sfCredentialType, ripple::strUnHex(std::string(credType[i])).value() + ripple::sfCredentialType, + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *ripple::strUnHex(std::string(credType[i])) ); arr.push_back(credential); } diff --git a/tests/common/util/TestWebSocketClient.cpp b/tests/common/util/TestWebSocketClient.cpp index 731ae723a..71f294d57 100644 --- a/tests/common/util/TestWebSocketClient.cpp +++ b/tests/common/util/TestWebSocketClient.cpp @@ -119,6 +119,7 @@ WebServerSslSyncClient::connect(std::string const& host, std::string const& port void WebServerSslSyncClient::disconnect() { + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) ws_->close(boost::beast::websocket::close_code::normal); } @@ -126,8 +127,8 @@ std::string WebServerSslSyncClient::syncPost(std::string const& body) { boost::beast::flat_buffer buffer; - ws_->write(net::buffer(std::string(body))); - ws_->read(buffer); + ws_->write(net::buffer(std::string(body))); // NOLINT(bugprone-unchecked-optional-access) + ws_->read(buffer); // NOLINT(bugprone-unchecked-optional-access) return boost::beast::buffers_to_string(buffer.data()); } diff --git a/tests/common/util/TestWsServer.hpp b/tests/common/util/TestWsServer.hpp index efc6c7b56..0017b958c 100644 --- a/tests/common/util/TestWsServer.hpp +++ b/tests/common/util/TestWsServer.hpp @@ -46,7 +46,7 @@ public: std::optional close(boost::asio::yield_context yield); - std::vector const& + [[nodiscard]] std::vector const& headers() const; void @@ -65,7 +65,7 @@ class TestWsServer { public: TestWsServer(boost::asio::io_context& context, std::string const& host); - std::string + [[nodiscard]] std::string port() const; std::expected diff --git a/tests/integration/data/BackendFactoryTests.cpp b/tests/integration/data/BackendFactoryTests.cpp index 1a245c8f9..1471f8806 100644 --- a/tests/integration/data/BackendFactoryTests.cpp +++ b/tests/integration/data/BackendFactoryTests.cpp @@ -81,7 +81,7 @@ public: // drop the keyspace for next test data::cassandra::Handle const handle{TestGlobals::instance().backendHost}; EXPECT_TRUE(handle.connect()); - handle.execute("DROP KEYSPACE " + std::string{kKEYSPACE}); + EXPECT_TRUE(handle.execute("DROP KEYSPACE IF EXISTS " + std::string{kKEYSPACE})); } }; @@ -98,7 +98,7 @@ TEST_F(BackendCassandraFactoryTest, CreateCassandraBackendDBDisconnect) {"database": { "type": "cassandra", "cassandra": { - "contact_points": "127.0.0.2" + "contact_points": "128.0.2.1" } }} )JSON"); @@ -120,16 +120,16 @@ TEST_F(BackendCassandraFactoryTestWithDB, CreateCassandraBackend) // insert range table data::cassandra::Handle const handle{TestGlobals::instance().backendHost}; EXPECT_TRUE(handle.connect()); - handle.execute( + EXPECT_TRUE(handle.execute( fmt::format( "INSERT INTO {}.ledger_range (is_latest, sequence) VALUES (False, 100)", kKEYSPACE ) - ); - handle.execute( + )); + EXPECT_TRUE(handle.execute( fmt::format( "INSERT INTO {}.ledger_range (is_latest, sequence) VALUES (True, 500)", kKEYSPACE ) - ); + )); } { @@ -138,7 +138,10 @@ TEST_F(BackendCassandraFactoryTestWithDB, CreateCassandraBackend) EXPECT_TRUE(backend); auto const range = backend->fetchLedgerRange(); + ASSERT_TRUE(range.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(range->minSequence, 100); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(range->maxSequence, 500); } } diff --git a/tests/integration/data/cassandra/BackendTests.cpp b/tests/integration/data/cassandra/BackendTests.cpp index 2309c6fd3..449572a41 100644 --- a/tests/integration/data/cassandra/BackendTests.cpp +++ b/tests/integration/data/cassandra/BackendTests.cpp @@ -123,7 +123,7 @@ public: // drop the keyspace for next test Handle const handle{TestGlobals::instance().backendHost}; EXPECT_TRUE(handle.connect()); - handle.execute("DROP KEYSPACE " + TestGlobals::instance().backendKeyspace); + EXPECT_TRUE(handle.execute("DROP KEYSPACE " + TestGlobals::instance().backendKeyspace)); } }; diff --git a/tests/integration/data/cassandra/BaseTests.cpp b/tests/integration/data/cassandra/BaseTests.cpp index 80c5f7493..af0b6a419 100644 --- a/tests/integration/data/cassandra/BaseTests.cpp +++ b/tests/integration/data/cassandra/BaseTests.cpp @@ -111,7 +111,7 @@ TEST_F(BackendCassandraBaseTest, ConnectionFailTimeout) Settings settings; settings.connectionTimeout = std::chrono::milliseconds{30}; settings.connectionInfo = - Settings::ContactPoints{.contactPoints = "127.0.0.2", .port = std::nullopt}; + Settings::ContactPoints{.contactPoints = "128.0.2.1", .port = std::nullopt}; Handle const handle{settings}; auto const f = handle.asyncConnect(); diff --git a/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp b/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp index b1d291eac..ecf46fb73 100644 --- a/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp +++ b/tests/integration/migration/cassandra/CassandraMigrationManagerTests.cpp @@ -152,7 +152,7 @@ public: // drop the keyspace Handle const handle{TestGlobals::instance().backendHost}; EXPECT_TRUE(handle.connect()); - handle.execute("DROP KEYSPACE " + TestGlobals::instance().backendKeyspace); + EXPECT_TRUE(handle.execute("DROP KEYSPACE " + TestGlobals::instance().backendKeyspace)); } }; @@ -173,28 +173,28 @@ TEST_F(MigrationCassandraManagerCleanDBTest, AllMigratorStatusBeforeAnyMigration { auto const status = testMigrationManager_->allMigratorsStatusPairs(); EXPECT_EQ(status.size(), 4); - EXPECT_EQ(std::get<1>(status[0]), MigratorStatus::NotMigrated); - EXPECT_EQ(std::get<1>(status[1]), MigratorStatus::NotMigrated); - EXPECT_EQ(std::get<1>(status[2]), MigratorStatus::NotMigrated); - EXPECT_EQ(std::get<1>(status[3]), MigratorStatus::NotMigrated); + EXPECT_EQ(std::get<1>(status[0]), MigratorStatus::Status::NotMigrated); + EXPECT_EQ(std::get<1>(status[1]), MigratorStatus::Status::NotMigrated); + EXPECT_EQ(std::get<1>(status[2]), MigratorStatus::Status::NotMigrated); + EXPECT_EQ(std::get<1>(status[3]), MigratorStatus::Status::NotMigrated); } TEST_F(MigrationCassandraManagerCleanDBTest, MigratorStatus) { auto status = testMigrationManager_->getMigratorStatusByName("ExampleObjectsMigrator"); - EXPECT_EQ(status, MigratorStatus::NotMigrated); + EXPECT_EQ(status, MigratorStatus::Status::NotMigrated); status = testMigrationManager_->getMigratorStatusByName("ExampleTransactionsMigrator"); - EXPECT_EQ(status, MigratorStatus::NotMigrated); + EXPECT_EQ(status, MigratorStatus::Status::NotMigrated); status = testMigrationManager_->getMigratorStatusByName("ExampleLedgerMigrator"); - EXPECT_EQ(status, MigratorStatus::NotMigrated); + EXPECT_EQ(status, MigratorStatus::Status::NotMigrated); status = testMigrationManager_->getMigratorStatusByName("ExampleDropTableMigrator"); - EXPECT_EQ(status, MigratorStatus::NotMigrated); + EXPECT_EQ(status, MigratorStatus::Status::NotMigrated); status = testMigrationManager_->getMigratorStatusByName("NonExistentMigrator"); - EXPECT_EQ(status, MigratorStatus::NotKnown); + EXPECT_EQ(status, MigratorStatus::Status::NotKnown); } // The test suite for testing migration process for ExampleTransactionsMigrator. In this test suite, @@ -217,7 +217,7 @@ TEST_F(MigrationCassandraManagerTxTableTest, MigrateExampleTransactionsMigrator) constexpr auto kTRANSACTIONS_MIGRATOR_NAME = "ExampleTransactionsMigrator"; EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kTRANSACTIONS_MIGRATOR_NAME), - MigratorStatus::NotMigrated + MigratorStatus::Status::NotMigrated ); ExampleTransactionsMigrator::count = 0; @@ -241,24 +241,27 @@ TEST_F(MigrationCassandraManagerTxTableTest, MigrateExampleTransactionsMigrator) auto txType = getTxType( ripple::uint256("CEECF7E516F8A53C5D32A357B737ED54D3186FDD510B1973D908AD8D93AD8E00") ); - EXPECT_TRUE(txType.has_value()); + ASSERT_TRUE(txType.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(txType.value(), "OracleSet"); txType = getTxType( ripple::uint256("35DBFB1A88DE17EBD2BCE37F6E1FD6D3B9887C92B7933ED2FCF2A84E9138B7CA") ); - EXPECT_TRUE(txType.has_value()); + ASSERT_TRUE(txType.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(txType.value(), "Payment"); txType = getTxType( ripple::uint256("FCACE9D00625FA3BCC5316078324EA153EC8551243AC1701D496CC1CA2B8A474") ); - EXPECT_TRUE(txType.has_value()); + ASSERT_TRUE(txType.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(txType.value(), "AMMCreate"); EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kTRANSACTIONS_MIGRATOR_NAME), - MigratorStatus::Migrated + MigratorStatus::Status::Migrated ); } @@ -281,7 +284,7 @@ TEST_F(MigrationCassandraManagerObjectsTableTest, MigrateExampleObjectsMigrator) constexpr auto kOBJECTS_MIGRATOR_NAME = "ExampleObjectsMigrator"; EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kOBJECTS_MIGRATOR_NAME), - MigratorStatus::NotMigrated + MigratorStatus::Status::NotMigrated ); testMigrationManager_->runMigration(kOBJECTS_MIGRATOR_NAME); @@ -291,7 +294,7 @@ TEST_F(MigrationCassandraManagerObjectsTableTest, MigrateExampleObjectsMigrator) EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kOBJECTS_MIGRATOR_NAME), - MigratorStatus::Migrated + MigratorStatus::Status::Migrated ); } @@ -315,13 +318,13 @@ TEST_F(MigrationCassandraManagerLedgerTableTest, MigrateExampleLedgerMigrator) constexpr auto kHEADER_MIGRATOR_NAME = "ExampleLedgerMigrator"; EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kHEADER_MIGRATOR_NAME), - MigratorStatus::NotMigrated + MigratorStatus::Status::NotMigrated ); testMigrationManager_->runMigration(kHEADER_MIGRATOR_NAME); EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kHEADER_MIGRATOR_NAME), - MigratorStatus::Migrated + MigratorStatus::Status::Migrated ); auto const newTableSize = data::synchronous([&](auto ctx) { @@ -357,7 +360,7 @@ TEST_F(MigrationCassandraManagerDropTableTest, MigrateDropTableMigrator) constexpr auto kDROP_TABLE_MIGRATOR_NAME = "ExampleDropTableMigrator"; EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kDROP_TABLE_MIGRATOR_NAME), - MigratorStatus::NotMigrated + MigratorStatus::Status::NotMigrated ); auto const beforeDropSize = @@ -367,7 +370,7 @@ TEST_F(MigrationCassandraManagerDropTableTest, MigrateDropTableMigrator) testMigrationManager_->runMigration(kDROP_TABLE_MIGRATOR_NAME); EXPECT_EQ( testMigrationManager_->getMigratorStatusByName(kDROP_TABLE_MIGRATOR_NAME), - MigratorStatus::Migrated + MigratorStatus::Status::Migrated ); auto const newTableSize = diff --git a/tests/unit/cluster/ClioNodeTests.cpp b/tests/unit/cluster/ClioNodeTests.cpp index 69a2dd9a2..c380c2dff 100644 --- a/tests/unit/cluster/ClioNodeTests.cpp +++ b/tests/unit/cluster/ClioNodeTests.cpp @@ -25,7 +25,8 @@ using namespace cluster; struct ClioNodeTest : testing::Test { std::string const updateTimeStr = "2015-05-15T12:00:00Z"; std::chrono::system_clock::time_point const updateTime = - util::systemTpFromUtcStr(updateTimeStr, ClioNode::kTIME_FORMAT).value(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *util::systemTpFromUtcStr(updateTimeStr, ClioNode::kTIME_FORMAT); }; TEST_F(ClioNodeTest, Serialization) diff --git a/tests/unit/data/LedgerCacheTests.cpp b/tests/unit/data/LedgerCacheTests.cpp index 69d19f59e..6a93b9ac6 100644 --- a/tests/unit/data/LedgerCacheTests.cpp +++ b/tests/unit/data/LedgerCacheTests.cpp @@ -129,11 +129,11 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFile) auto const blob1 = cache.get(key1, kLEDGER_SEQ); ASSERT_TRUE(blob1.has_value()); - EXPECT_EQ(blob1.value(), objs.front().data); + EXPECT_EQ(blob1.value(), objs.front().data); // NOLINT(bugprone-unchecked-optional-access) auto const blob2 = cache.get(key2, kLEDGER_SEQ); ASSERT_TRUE(blob2.has_value()); - EXPECT_EQ(blob2.value(), objs.back().data); + EXPECT_EQ(blob2.value(), objs.back().data); // NOLINT(bugprone-unchecked-optional-access) auto const tmpFile = TmpFile::empty(); auto const saveResult = cache.saveToFile(tmpFile.path); @@ -149,11 +149,11 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFile) auto const loadedBlob1 = newCache.get(key1, kLEDGER_SEQ); ASSERT_TRUE(loadedBlob1.has_value()); - EXPECT_EQ(loadedBlob1.value(), blob1); + EXPECT_EQ(loadedBlob1.value(), blob1); // NOLINT(bugprone-unchecked-optional-access) auto const loadedBlob2 = newCache.get(key2, kLEDGER_SEQ); ASSERT_TRUE(loadedBlob2.has_value()); - EXPECT_EQ(loadedBlob2.value(), blob2); + EXPECT_EQ(loadedBlob2.value(), blob2); // NOLINT(bugprone-unchecked-optional-access) EXPECT_EQ(newCache.latestLedgerSequence(), cache.latestLedgerSequence()); } @@ -174,10 +174,11 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFileWithDeletedObjects) auto const blob2 = cache.get(key2, kLEDGER_SEQ); ASSERT_TRUE(blob2.has_value()); - EXPECT_EQ(blob2.value(), objs.back().data); + EXPECT_EQ(blob2.value(), objs.back().data); // NOLINT(bugprone-unchecked-optional-access) auto const deletedBlob = cache.getDeleted(key1, kLEDGER_SEQ - 1); ASSERT_TRUE(deletedBlob.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(deletedBlob.value(), objs.front().data); // Save and load @@ -192,6 +193,7 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFileWithDeletedObjects) // Verify deleted object is preserved auto const loadedDeletedBlob = newCache.getDeleted(key1, kLEDGER_SEQ - 1); ASSERT_TRUE(loadedDeletedBlob.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(loadedDeletedBlob.value(), deletedBlob); // Verify active object @@ -200,7 +202,7 @@ TEST_F(LedgerCacheSaveLoadTest, saveAndLoadFromFileWithDeletedObjects) auto const loadedBlob2 = newCache.get(key2, kLEDGER_SEQ); ASSERT_TRUE(loadedBlob2.has_value()); - EXPECT_EQ(loadedBlob2.value(), blob2); + EXPECT_EQ(loadedBlob2.value(), blob2); // NOLINT(bugprone-unchecked-optional-access) EXPECT_TRUE(newCache.isFull()); EXPECT_EQ(newCache.latestLedgerSequence(), cache.latestLedgerSequence()); diff --git a/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp b/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp index 046aab257..a381802e0 100644 --- a/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp +++ b/tests/unit/data/cassandra/LedgerHeaderCacheTests.cpp @@ -30,7 +30,7 @@ TEST_F(FetchLedgerCacheTest, CanStoreAndRetrieveEntry) auto const result = cache_.get(); ASSERT_TRUE(result.has_value()); - EXPECT_EQ(result.value(), entry); + EXPECT_EQ(result.value(), entry); // NOLINT(bugprone-unchecked-optional-access) } TEST_F(FetchLedgerCacheTest, PutOverwritesPreviousEntry) @@ -46,5 +46,5 @@ TEST_F(FetchLedgerCacheTest, PutOverwritesPreviousEntry) auto const result = cache_.get(); ASSERT_TRUE(result.has_value()); - EXPECT_EQ(result.value(), entry2); + EXPECT_EQ(result.value(), entry2); // NOLINT(bugprone-unchecked-optional-access) } diff --git a/tests/unit/data/impl/OutputFileTests.cpp b/tests/unit/data/impl/OutputFileTests.cpp index 8fc7f1705..ee7f970f2 100644 --- a/tests/unit/data/impl/OutputFileTests.cpp +++ b/tests/unit/data/impl/OutputFileTests.cpp @@ -18,7 +18,7 @@ using namespace data::impl; struct OutputFileTest : ::testing::Test { TmpFile tmpFile = TmpFile::empty(); - std::string + [[nodiscard]] std::string readFileContents() const { std::ifstream ifs(tmpFile.path, std::ios::binary); diff --git a/tests/unit/etl/CacheLoaderSettingsTests.cpp b/tests/unit/etl/CacheLoaderSettingsTests.cpp index 0c9e08df3..cef6243da 100644 --- a/tests/unit/etl/CacheLoaderSettingsTests.cpp +++ b/tests/unit/etl/CacheLoaderSettingsTests.cpp @@ -130,6 +130,7 @@ TEST_F(CacheLoaderSettingsTest, CacheFilePathCorrectlyPropagatedThroughConfig) auto const settings = makeCacheLoaderSettings(cfg); ASSERT_TRUE(settings.cacheFileSettings.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(settings.cacheFileSettings->path, kCACHE_FILE_PATH); } @@ -152,5 +153,6 @@ TEST_F(CacheLoaderSettingsTest, MaxSequenceLagPropagatedThoughConfig) auto const settings = makeCacheLoaderSettings(cfg); ASSERT_TRUE(settings.cacheFileSettings.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(settings.cacheFileSettings->maxAge, seq); } diff --git a/tests/unit/etl/ETLStateTests.cpp b/tests/unit/etl/ETLStateTests.cpp index 7ed73024d..b49d74fd4 100644 --- a/tests/unit/etl/ETLStateTests.cpp +++ b/tests/unit/etl/ETLStateTests.cpp @@ -38,7 +38,7 @@ TEST_F(ETLStateTest, NetworkIdValid) EXPECT_CALL(source, forwardToRippled).WillOnce(Return(json.as_object())); auto const state = etl::ETLState::fetchETLStateFromSource(source); ASSERT_TRUE(state.has_value()); - EXPECT_EQ(state->networkID, 12); + EXPECT_EQ(state->networkID, 12); // NOLINT(bugprone-unchecked-optional-access) } TEST_F(ETLStateTest, NetworkIdInvalid) @@ -55,7 +55,7 @@ TEST_F(ETLStateTest, NetworkIdInvalid) EXPECT_CALL(source, forwardToRippled).WillOnce(Return(json.as_object())); auto const state = etl::ETLState::fetchETLStateFromSource(source); ASSERT_TRUE(state.has_value()); - EXPECT_NE(state->networkID, 12); + EXPECT_NE(state->networkID, 12); // NOLINT(bugprone-unchecked-optional-access) } TEST_F(ETLStateTest, ResponseHasError) diff --git a/tests/unit/etl/ExtractionTests.cpp b/tests/unit/etl/ExtractionTests.cpp index d24a36f7d..1f6d70f8a 100644 --- a/tests/unit/etl/ExtractionTests.cpp +++ b/tests/unit/etl/ExtractionTests.cpp @@ -330,9 +330,9 @@ TEST_F(ExtractionTests, MultipleSuccessors) auto res = maybeExtractSuccessors(data); ASSERT_TRUE(res.has_value()); - EXPECT_EQ(res->size(), 10); + EXPECT_EQ(res->size(), 10); // NOLINT(bugprone-unchecked-optional-access) - for (auto const& successor : res.value()) { + for (auto const& successor : res.value()) { // NOLINT(bugprone-unchecked-optional-access) EXPECT_EQ(successor.firstBook, expected.firstBook); EXPECT_EQ(successor.bookBase, expected.bookBase); } @@ -395,11 +395,13 @@ TEST_F(ExtractorTests, ExtractLedgerWithDiffWithResult) auto res = extractor.extractLedgerWithDiff(kSEQ); EXPECT_TRUE(res.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(res->objects.size(), 10); EXPECT_EQ(res->transactions.size(), 10); EXPECT_TRUE(res->successors.has_value()); EXPECT_EQ(res->successors->size(), 10); EXPECT_FALSE(res->edgeKeys.has_value()); // this is set separately in ETL + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(ExtractorTests, ExtractLedgerOnlyWithResult) @@ -410,8 +412,10 @@ TEST_F(ExtractorTests, ExtractLedgerOnlyWithResult) auto res = extractor.extractLedgerOnly(kSEQ); EXPECT_TRUE(res.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_TRUE(res->objects.empty()); EXPECT_EQ(res->transactions.size(), 10); EXPECT_FALSE(res->successors.has_value()); EXPECT_FALSE(res->edgeKeys.has_value()); // this is set separately in ETL + // NOLINTEND(bugprone-unchecked-optional-access) } diff --git a/tests/unit/etl/LedgerPublisherTests.cpp b/tests/unit/etl/LedgerPublisherTests.cpp index 53ca08840..90b7ba14a 100644 --- a/tests/unit/etl/LedgerPublisherTests.cpp +++ b/tests/unit/etl/LedgerPublisherTests.cpp @@ -62,8 +62,10 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderSkipDueToAge) publisher.publish(dummyLedgerHeader); // Verify last published sequence is set immediately - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); // Since age > MAX_LEDGER_AGE_SECONDS, these should not be called EXPECT_CALL(*backend_, doFetchLedgerObject).Times(0); @@ -96,8 +98,10 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderWithinAgeLimit) publisher.publish(dummyLedgerHeader); // Verify last published sequence is set immediately - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); ctx.join(); EXPECT_TRUE(publisher.lastPublishAgeSeconds() <= 1); @@ -111,8 +115,10 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderIsWritingTrue) auto publisher = impl::LedgerPublisher(ctx, backend_, mockSubscriptionManagerPtr, dummyState); publisher.publish(dummyLedgerHeader); - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); ctx.join(); @@ -152,8 +158,10 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderInRange) EXPECT_CALL(*mockSubscriptionManagerPtr, pubTransaction); publisher.publish(dummyLedgerHeader); - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); ctx.join(); @@ -198,8 +206,10 @@ TEST_F(ETLLedgerPublisherTest, PublishLedgerHeaderCloseTimeGreaterThanNow) EXPECT_CALL(*mockSubscriptionManagerPtr, pubTransaction); publisher.publish(dummyLedgerHeader); - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); ctx.join(); @@ -289,8 +299,10 @@ TEST_F(ETLLedgerPublisherTest, PublishMultipleTxInOrder) EXPECT_CALL(*mockSubscriptionManagerPtr, pubTransaction(t1, _)).InSequence(s); publisher.publish(dummyLedgerHeader); - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); ctx.join(); @@ -312,8 +324,10 @@ TEST_F(ETLLedgerPublisherTest, PublishVeryOldLedgerShouldSkip) EXPECT_CALL(*mockSubscriptionManagerPtr, pubTransaction).Times(0); publisher.publish(dummyLedgerHeader); - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ); ctx.join(); } @@ -360,8 +374,10 @@ TEST_F(ETLLedgerPublisherTest, PublishMultipleLedgersInQuickSuccession) publisher.publish(dummyLedgerHeader1); publisher.publish(dummyLedgerHeader2); - EXPECT_TRUE(publisher.getLastPublishedSequence()); - EXPECT_EQ(publisher.getLastPublishedSequence().value(), kSEQ + 1); + auto const seq = publisher.getLastPublishedSequence(); + ASSERT_TRUE(seq.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(seq.value(), kSEQ + 1); ctx.join(); } diff --git a/tests/unit/etl/LoadBalancerTests.cpp b/tests/unit/etl/LoadBalancerTests.cpp index 2c03848ca..7034ea7dc 100644 --- a/tests/unit/etl/LoadBalancerTests.cpp +++ b/tests/unit/etl/LoadBalancerTests.cpp @@ -809,6 +809,36 @@ TEST_F(LoadBalancerForwardToRippledPrometheusTests, source0Fails) }); } +TEST_F(LoadBalancerForwardToRippledPrometheusTests, adminRequestAlwaysCacheMiss) +{ + configJson_.as_object()["forwarding"] = boost::json::object{{"cache_timeout", 10.}}; + EXPECT_CALL(sourceFactory_, makeSource).Times(2); + auto loadBalancer = makeLoadBalancer(); + + auto const request = boost::json::object{{"command", "server_info"}}; + + auto& cacheMissCounter = makeMock("forwarding_cache_miss_counter", ""); + auto& successDurationCounter = + makeMock("forwarding_duration_milliseconds_counter", "{status=\"success\"}"); + + EXPECT_CALL(cacheMissCounter, add(1)).Times(2); + EXPECT_CALL(successDurationCounter, add(testing::_)).Times(2); + + EXPECT_CALL( + sourceFactory_.sourceAt(0), + forwardToRippled( + request, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ + ) + ) + .Times(2) + .WillRepeatedly(Return(response_)); + + runSpawn([&](boost::asio::yield_context yield) { + EXPECT_EQ(loadBalancer->forwardToRippled(request, clientIP_, true, yield), response_); + EXPECT_EQ(loadBalancer->forwardToRippled(request, clientIP_, true, yield), response_); + }); +} + struct LoadBalancerForwardToRippledErrorTestBundle { std::string testName; rpc::ClioError firstSourceError; @@ -906,6 +936,59 @@ TEST_F(LoadBalancerForwardToRippledTests, forwardingCacheEnabled) }); } +TEST_F(LoadBalancerForwardToRippledTests, adminRequestBypassesForwardingCache) +{ + configJson_.as_object()["forwarding"] = boost::json::object{{"cache_timeout", 10.}}; + EXPECT_CALL(sourceFactory_, makeSource).Times(2); + auto loadBalancer = makeLoadBalancer(); + + auto const request = boost::json::object{{"command", "server_info"}}; + + EXPECT_CALL( + sourceFactory_.sourceAt(0), + forwardToRippled( + request, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ + ) + ) + .Times(2) + .WillRepeatedly(Return(response_)); + + runSpawn([&](boost::asio::yield_context yield) { + EXPECT_EQ(loadBalancer->forwardToRippled(request, clientIP_, true, yield), response_); + EXPECT_EQ(loadBalancer->forwardToRippled(request, clientIP_, true, yield), response_); + }); +} + +TEST_F(LoadBalancerForwardToRippledTests, adminResponseNotCachedForSubsequentUserRequest) +{ + configJson_.as_object()["forwarding"] = boost::json::object{{"cache_timeout", 10.}}; + EXPECT_CALL(sourceFactory_, makeSource).Times(2); + auto loadBalancer = makeLoadBalancer(); + + auto const request = boost::json::object{{"command", "server_info"}}; + + EXPECT_CALL( + sourceFactory_.sourceAt(0), + forwardToRippled( + request, clientIP_, LoadBalancer::kADMIN_FORWARDING_X_USER_VALUE, testing::_ + ) + ) + .WillOnce(Return(response_)); + EXPECT_CALL( + sourceFactory_.sourceAt(0), + forwardToRippled( + request, clientIP_, LoadBalancer::kUSER_FORWARDING_X_USER_VALUE, testing::_ + ) + ) + .WillOnce(Return(response_)); + + runSpawn([&](boost::asio::yield_context yield) { + EXPECT_EQ(loadBalancer->forwardToRippled(request, clientIP_, true, yield), response_); + // User request must reach the source, not be served from the admin response + EXPECT_EQ(loadBalancer->forwardToRippled(request, clientIP_, false, yield), response_); + }); +} + TEST_F(LoadBalancerForwardToRippledTests, forwardingCacheDisabledOnLedgerClosedHookCalled) { EXPECT_CALL(sourceFactory_, makeSource).Times(2); diff --git a/tests/unit/etl/LoadingTests.cpp b/tests/unit/etl/LoadingTests.cpp index 89322ae5b..747aa5746 100644 --- a/tests/unit/etl/LoadingTests.cpp +++ b/tests/unit/etl/LoadingTests.cpp @@ -92,9 +92,11 @@ TEST_F(LoadingTests, LoadInitialLedger) auto const res = loader_.loadInitialLedger(data); EXPECT_TRUE(res.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ( rpc::ledgerHeaderToBlob(res.value(), true), rpc::ledgerHeaderToBlob(data.header, true) ); + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(LoadingTests, LoadSuccess) diff --git a/tests/unit/etl/NFTHelpersTests.cpp b/tests/unit/etl/NFTHelpersTests.cpp index 2950577a4..938cba80e 100644 --- a/tests/unit/etl/NFTHelpersTests.cpp +++ b/tests/unit/etl/NFTHelpersTests.cpp @@ -69,7 +69,8 @@ protected: if (sttx.getTxnType() == ripple::ttNFTOKEN_MINT || sttx.getTxnType() == ripple::ttNFTOKEN_MODIFY) { - EXPECT_TRUE(data.uri.has_value()); + ASSERT_TRUE(data.uri.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(*data.uri, sttx.getFieldVL(ripple::sfURI)); } else { EXPECT_FALSE(data.uri.has_value()); @@ -149,6 +150,8 @@ TEST_F(NFTHelpersTest, NFTModifyWithURI) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, std::nullopt); } @@ -162,6 +165,8 @@ TEST_F(NFTHelpersTest, NFTModifyWithoutURI) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, std::nullopt); } @@ -176,6 +181,8 @@ TEST_F(NFTHelpersTest, NFTMintFromModifiedNode) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -209,6 +216,8 @@ TEST_F(NFTHelpersTest, NFTMintFromCreatedNode) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -225,6 +234,8 @@ TEST_F(NFTHelpersTest, NFTMintWithoutUriField) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -255,6 +266,8 @@ TEST_F(NFTHelpersTest, NFTBurnFromDeletedNode) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -284,6 +297,8 @@ TEST_F(NFTHelpersTest, NFTBurnFromModifiedNode) EXPECT_EQ(nftTxs.size(), 1); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -365,6 +380,8 @@ TEST_F(NFTHelpersTest, NFTAcceptBuyerOffer) EXPECT_EQ(nftTxs.size(), 1); EXPECT_TRUE(nftDatas); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -397,6 +414,8 @@ TEST_F(NFTHelpersTest, NFTAcceptSellerOfferFromCreatedNode) EXPECT_EQ(nftTxs.size(), 1); EXPECT_TRUE(nftDatas); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -413,6 +432,8 @@ TEST_F(NFTHelpersTest, NFTAcceptSellerOfferFromModifiedNode) EXPECT_EQ(nftTxs.size(), 1); EXPECT_TRUE(nftDatas); verifyNFTTransactionsData(nftTxs[0], sttx, txMeta, kNFT_ID); + ASSERT_TRUE(nftDatas.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) verifyNFTsData(*nftDatas, sttx, txMeta, kNFT_ID, kACCOUNT); } @@ -523,14 +544,14 @@ TEST_F(NFTHelpersTest, NFTDataFromLedgerObject) EXPECT_EQ(nftDatas.size(), 2); EXPECT_EQ(nftDatas[0].tokenID, ripple::uint256(kNFT_ID)); - EXPECT_EQ(*(nftDatas[0].uri), uri1Blob); + EXPECT_EQ(*(nftDatas[0].uri), uri1Blob); // NOLINT(bugprone-unchecked-optional-access) EXPECT_FALSE(nftDatas[0].onlyUriChanged); EXPECT_EQ(nftDatas[0].owner, account); EXPECT_EQ(nftDatas[0].ledgerSequence, kSEQ); EXPECT_FALSE(nftDatas[0].isBurned); EXPECT_EQ(nftDatas[1].tokenID, ripple::uint256(kNFT_ID2)); - EXPECT_EQ(*(nftDatas[1].uri), uri2Blob); + EXPECT_EQ(*(nftDatas[1].uri), uri2Blob); // NOLINT(bugprone-unchecked-optional-access) EXPECT_FALSE(nftDatas[1].onlyUriChanged); EXPECT_EQ(nftDatas[1].owner, account); EXPECT_EQ(nftDatas[1].ledgerSequence, kSEQ); diff --git a/tests/unit/etl/SchedulingTests.cpp b/tests/unit/etl/SchedulingTests.cpp index ae0a8958f..3e38c24b4 100644 --- a/tests/unit/etl/SchedulingTests.cpp +++ b/tests/unit/etl/SchedulingTests.cpp @@ -48,7 +48,7 @@ TEST_F(ForwardSchedulerTests, ExhaustsSchedulerIfMostRecentLedgerIsNewerThanRequ auto maybeTask = scheduler.next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } auto const empty = scheduler.next(); @@ -66,7 +66,7 @@ TEST_F(ForwardSchedulerTests, ReturnsNulloptIfMostRecentLedgerIsOlderThanRequest auto const maybeTask = scheduler.next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } for (auto i = 0u; i < 5u; ++i) @@ -81,7 +81,7 @@ TEST(BackfillSchedulerTests, ExhaustsSchedulerUntilMinSeqReached) auto maybeTask = scheduler.next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } auto const empty = scheduler.next(); @@ -96,7 +96,7 @@ TEST(BackfillSchedulerTests, ExhaustsSchedulerUntilDefaultMinValueReached) auto const maybeTask = scheduler.next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } auto const empty = scheduler.next(); @@ -121,7 +121,7 @@ TEST(SchedulerChainTests, ExhaustsOneGenerator) auto const maybeTask = scheduler->next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } auto const empty = scheduler->next(); @@ -158,13 +158,13 @@ TEST(SchedulerChainTests, ExhaustsFirstSchedulerBeforeUsingSecond) auto const maybeTask = scheduler->next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } for (auto i = 10u; i > 0u; --i) { auto const maybeTask = scheduler->next(); EXPECT_TRUE(maybeTask.has_value()); - EXPECT_EQ(maybeTask->seq, i); + EXPECT_EQ(maybeTask->seq, i); // NOLINT(bugprone-unchecked-optional-access) } auto const empty = scheduler->next(); diff --git a/tests/unit/etl/ext/SuccessorTests.cpp b/tests/unit/etl/ext/SuccessorTests.cpp index 2b12145c4..183222011 100644 --- a/tests/unit/etl/ext/SuccessorTests.cpp +++ b/tests/unit/etl/ext/SuccessorTests.cpp @@ -455,11 +455,13 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsButNotBookDirAndNoSuccessor writeSuccessor(uint256ToString(secondKey), kSEQ, uint256ToString(data::kLAST_KEY)) ); - for (auto const& key : data.edgeKeys.value()) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) + for (auto const& key : *data.edgeKeys) { EXPECT_CALL(cache_, getSuccessor(*ripple::uint256::fromVoidChecked(key), kSEQ)) .InSequence(inSeq) .WillOnce(testing::Return(std::nullopt)); } + // NOLINTEND(bugprone-unchecked-optional-access) ext_.onInitialData(data); } @@ -502,12 +504,14 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsButNotBookDirAndSuccessorsF writeSuccessor(uint256ToString(secondKey), kSEQ, uint256ToString(data::kLAST_KEY)) ); - for (auto const& key : data.edgeKeys.value()) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) + for (auto const& key : *data.edgeKeys) { EXPECT_CALL(cache_, getSuccessor(*ripple::uint256::fromVoidChecked(key), kSEQ)) .InSequence(inSeq) .WillOnce(testing::Return(data::LedgerObject{.key = firstKey, .blob = {}})); EXPECT_CALL(*backend_, writeSuccessor(auto{key}, kSEQ, uint256ToString(firstKey))); } + // NOLINTEND(bugprone-unchecked-optional-access) ext_.onInitialData(data); } @@ -562,13 +566,15 @@ TEST_F(SuccessorExtTests, OnInitialDataWithSuccessorsAndBookDirAndSuccessorsForE *backend_, writeSuccessor(uint256ToString(bookBase), kSEQ, testing::_) ); // Called once because firstKey returned repeatedly above - for (auto const& key : data.edgeKeys.value()) { + // NOLINTBEGIN(bugprone-unchecked-optional-access) + for (auto const& key : *data.edgeKeys) { EXPECT_CALL(cache_, getSuccessor(*ripple::uint256::fromVoidChecked(key), kSEQ)) .InSequence(inSeq) .WillOnce(testing::Return(data::LedgerObject{.key = firstKey, .blob = {'1'}})); EXPECT_CALL(*backend_, writeSuccessor(auto{key}, kSEQ, uint256ToString(firstKey))) .InSequence(inSeq); } + // NOLINTEND(bugprone-unchecked-optional-access) ext_.onInitialData(data); } diff --git a/tests/unit/feed/SubscriptionManagerTests.cpp b/tests/unit/feed/SubscriptionManagerTests.cpp index 3c7f57061..328bdb9c4 100644 --- a/tests/unit/feed/SubscriptionManagerTests.cpp +++ b/tests/unit/feed/SubscriptionManagerTests.cpp @@ -120,10 +120,10 @@ TEST_F(SubscriptionManagerTest, ReportCurrentSubscriber) "book_changes": 2 })JSON"; web::SubscriptionContextPtr const session1 = std::make_shared(); - MockSession* mockSession1 = dynamic_cast(session1.get()); + auto const* mockSession1 = dynamic_cast(session1.get()); web::SubscriptionContextPtr session2 = std::make_shared(); - MockSession* mockSession2 = dynamic_cast(session2.get()); + auto const* mockSession2 = dynamic_cast(session2.get()); std::vector session2OnDisconnectSlots; ON_CALL(*mockSession2, onDisconnect).WillByDefault([&session2OnDisconnectSlots](auto slot) { session2OnDisconnectSlots.push_back(slot); diff --git a/tests/unit/migration/MigrationInspectorBaseTests.cpp b/tests/unit/migration/MigrationInspectorBaseTests.cpp index 91ca8c755..ec41447e9 100644 --- a/tests/unit/migration/MigrationInspectorBaseTests.cpp +++ b/tests/unit/migration/MigrationInspectorBaseTests.cpp @@ -41,12 +41,14 @@ TEST_F(MigrationInspectorBaseTest, AllStatus) EXPECT_EQ(status.size(), 2); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Migrated) + status, + std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Status::Migrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); } @@ -78,14 +80,14 @@ TEST_F(MigrationInspectorBaseTest, getMigratorStatusByName) .WillOnce(testing::Return("Migrated")); EXPECT_EQ( migrationInspector_->getMigratorStatusByName("SimpleTestMigrator"), - migration::MigratorStatus::Migrated + migration::MigratorStatus::Status::Migrated ); EXPECT_CALL(*backend_, fetchMigratorStatus("SimpleTestMigrator2", testing::_)) .WillOnce(testing::Return("NotMigrated")); EXPECT_EQ( migrationInspector_->getMigratorStatusByName("SimpleTestMigrator2"), - migration::MigratorStatus::NotMigrated + migration::MigratorStatus::Status::NotMigrated ); } diff --git a/tests/unit/migration/MigrationManagerBaseTests.cpp b/tests/unit/migration/MigrationManagerBaseTests.cpp index 7f8c9e268..a745eaf97 100644 --- a/tests/unit/migration/MigrationManagerBaseTests.cpp +++ b/tests/unit/migration/MigrationManagerBaseTests.cpp @@ -52,12 +52,14 @@ TEST_F(MigrationManagerBaseTest, AllStatus) EXPECT_EQ(status.size(), 2); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Migrated) + status, + std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Status::Migrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); } @@ -98,10 +100,10 @@ TEST_F(MigrationManagerBaseTest, getMigratorStatusByName) EXPECT_EQ( migrationManager->getMigratorStatusByName("SimpleTestMigrator"), - migration::MigratorStatus::Migrated + migration::MigratorStatus::Status::Migrated ); EXPECT_EQ( migrationManager->getMigratorStatusByName("SimpleTestMigrator2"), - migration::MigratorStatus::NotMigrated + migration::MigratorStatus::Status::NotMigrated ); } diff --git a/tests/unit/migration/MigratorRegisterTests.cpp b/tests/unit/migration/MigratorRegisterTests.cpp index fcfa67089..b52097550 100644 --- a/tests/unit/migration/MigratorRegisterTests.cpp +++ b/tests/unit/migration/MigratorRegisterTests.cpp @@ -44,7 +44,9 @@ TEST_F(MigratorRegisterTests, EmptyMigratorRegister) EmptyMigratorRegister migratorRegister(backend_); EXPECT_EQ(migratorRegister.getMigratorsStatus().size(), 0); EXPECT_EQ(migratorRegister.getMigratorNames().size(), 0); - EXPECT_EQ(migratorRegister.getMigratorStatus("unknown"), migration::MigratorStatus::NotKnown); + EXPECT_EQ( + migratorRegister.getMigratorStatus("unknown"), migration::MigratorStatus::Status::NotKnown + ); EXPECT_NO_THROW(migratorRegister.runMigrator("unknown", gCfg.getObject("migration"))); EXPECT_EQ(migratorRegister.getMigratorDescription("unknown"), "No Description"); } @@ -71,21 +73,26 @@ TEST_F(MultipleMigratorRegisterTests, GetMigratorsStatusWhenError) .Times(3) .WillRepeatedly(testing::Return(std::nullopt)); + ASSERT_TRUE(migratorRegister.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const status = migratorRegister->getMigratorsStatus(); EXPECT_EQ(status.size(), 3); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator3", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator3", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); } @@ -96,21 +103,26 @@ TEST_F(MultipleMigratorRegisterTests, GetMigratorsStatusWhenReturnInvalidStatus) .Times(3) .WillRepeatedly(testing::Return("Invalid")); + ASSERT_TRUE(migratorRegister.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const status = migratorRegister->getMigratorsStatus(); EXPECT_EQ(status.size(), 3); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator3", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator3", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); } @@ -124,21 +136,26 @@ TEST_F(MultipleMigratorRegisterTests, GetMigratorsStatusWhenOneMigrated) EXPECT_CALL(*backend_, fetchMigratorStatus("SimpleTestMigrator3", testing::_)) .WillOnce(testing::Return("NotMigrated")); + ASSERT_TRUE(migratorRegister.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const status = migratorRegister->getMigratorsStatus(); EXPECT_EQ(status.size(), 3); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Migrated) + status, + std::make_tuple("SimpleTestMigrator", migration::MigratorStatus::Status::Migrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator2", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); EXPECT_TRUE( std::ranges::find( - status, std::make_tuple("SimpleTestMigrator3", migration::MigratorStatus::NotMigrated) + status, + std::make_tuple("SimpleTestMigrator3", migration::MigratorStatus::Status::NotMigrated) ) != status.end() ); } @@ -150,14 +167,21 @@ TEST_F(MultipleMigratorRegisterTests, GetMigratorStatus) EXPECT_CALL(*backend_, fetchMigratorStatus("SimpleTestMigrator2", testing::_)) .WillOnce(testing::Return("NotMigrated")); - EXPECT_EQ(migratorRegister->getMigratorStatus("unknown"), migration::MigratorStatus::NotKnown); + ASSERT_TRUE(migratorRegister.has_value()); EXPECT_EQ( - migratorRegister->getMigratorStatus("SimpleTestMigrator"), - migration::MigratorStatus::Migrated + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + migratorRegister->getMigratorStatus("unknown"), + migration::MigratorStatus::Status::NotKnown ); EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + migratorRegister->getMigratorStatus("SimpleTestMigrator"), + migration::MigratorStatus::Status::Migrated + ); + EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) migratorRegister->getMigratorStatus("SimpleTestMigrator2"), - migration::MigratorStatus::NotMigrated + migration::MigratorStatus::Status::NotMigrated ); } @@ -167,19 +191,28 @@ TEST_F(MultipleMigratorRegisterTests, GetMigratorStatusWhenError) .Times(2) .WillRepeatedly(testing::Return(std::nullopt)); - EXPECT_EQ(migratorRegister->getMigratorStatus("unknown"), migration::MigratorStatus::NotKnown); + ASSERT_TRUE(migratorRegister.has_value()); EXPECT_EQ( - migratorRegister->getMigratorStatus("SimpleTestMigrator"), - migration::MigratorStatus::NotMigrated + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + migratorRegister->getMigratorStatus("unknown"), + migration::MigratorStatus::Status::NotKnown ); EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + migratorRegister->getMigratorStatus("SimpleTestMigrator"), + migration::MigratorStatus::Status::NotMigrated + ); + EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) migratorRegister->getMigratorStatus("SimpleTestMigrator2"), - migration::MigratorStatus::NotMigrated + migration::MigratorStatus::Status::NotMigrated ); } TEST_F(MultipleMigratorRegisterTests, Names) { + ASSERT_TRUE(migratorRegister.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto names = migratorRegister->getMigratorNames(); EXPECT_EQ(names.size(), 3); EXPECT_TRUE(std::ranges::find(names, "SimpleTestMigrator") != names.end()); @@ -189,12 +222,16 @@ TEST_F(MultipleMigratorRegisterTests, Names) TEST_F(MultipleMigratorRegisterTests, Description) { + ASSERT_TRUE(migratorRegister.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(migratorRegister->getMigratorDescription("unknown"), "No Description"); EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) migratorRegister->getMigratorDescription("SimpleTestMigrator"), "The migrator for version 0 -> 1" ); EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) migratorRegister->getMigratorDescription("SimpleTestMigrator2"), "The migrator for version 1 -> 2" ); @@ -203,31 +240,40 @@ TEST_F(MultipleMigratorRegisterTests, Description) TEST_F(MultipleMigratorRegisterTests, RunUnknownMigrator) { EXPECT_CALL(*backend_, writeMigratorStatus(testing::_, testing::_)).Times(0); - EXPECT_NO_THROW(migratorRegister->runMigrator("unknown", gCfg.getObject("migration"))); + EXPECT_NO_THROW( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + migratorRegister->runMigrator("unknown", gCfg.getObject("migration")) + ); } TEST_F(MultipleMigratorRegisterTests, MigrateNormalMigrator) { EXPECT_CALL(*backend_, writeMigratorStatus("SimpleTestMigrator", "Migrated")).Times(1); EXPECT_NO_THROW( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) migratorRegister->runMigrator("SimpleTestMigrator", gCfg.getObject("migration")) ); } TEST_F(MultipleMigratorRegisterTests, canBlock) { + ASSERT_TRUE(migratorRegister.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto canBlock = migratorRegister->canMigratorBlockClio("SimpleTestMigrator"); - EXPECT_TRUE(canBlock); - EXPECT_TRUE(*canBlock); + ASSERT_TRUE(canBlock.has_value()); + EXPECT_TRUE(*canBlock); // NOLINT(bugprone-unchecked-optional-access) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) canBlock = migratorRegister->canMigratorBlockClio("SimpleTestMigrator2"); - EXPECT_TRUE(canBlock); - EXPECT_FALSE(*canBlock); + ASSERT_TRUE(canBlock.has_value()); + EXPECT_FALSE(*canBlock); // NOLINT(bugprone-unchecked-optional-access) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) canBlock = migratorRegister->canMigratorBlockClio("SimpleTestMigrator3"); - EXPECT_TRUE(canBlock); - EXPECT_FALSE(*canBlock); + ASSERT_TRUE(canBlock.has_value()); + EXPECT_FALSE(*canBlock); // NOLINT(bugprone-unchecked-optional-access) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) canBlock = migratorRegister->canMigratorBlockClio("NotAMigrator"); - EXPECT_FALSE(canBlock); + EXPECT_FALSE(canBlock.has_value()); } diff --git a/tests/unit/migration/MigratorStatusTests.cpp b/tests/unit/migration/MigratorStatusTests.cpp index ff14a7b7d..e8bcbae54 100644 --- a/tests/unit/migration/MigratorStatusTests.cpp +++ b/tests/unit/migration/MigratorStatusTests.cpp @@ -4,37 +4,41 @@ TEST(MigratiorStatus, ToString) { - migration::MigratorStatus status(migration::MigratorStatus::Migrated); + migration::MigratorStatus status(migration::MigratorStatus::Status::Migrated); EXPECT_EQ(status.toString(), "Migrated"); - status = migration::MigratorStatus(migration::MigratorStatus::NotMigrated); + status = migration::MigratorStatus(migration::MigratorStatus::Status::NotMigrated); EXPECT_EQ(status.toString(), "NotMigrated"); - status = migration::MigratorStatus(migration::MigratorStatus::NotKnown); + status = migration::MigratorStatus(migration::MigratorStatus::Status::NotKnown); EXPECT_EQ(status.toString(), "NotKnown"); } TEST(MigratiorStatus, FromString) { EXPECT_EQ( - migration::MigratorStatus::fromString("Migrated"), migration::MigratorStatus::Migrated + migration::MigratorStatus::fromString("Migrated"), + migration::MigratorStatus::Status::Migrated ); EXPECT_EQ( - migration::MigratorStatus::fromString("NotMigrated"), migration::MigratorStatus::NotMigrated + migration::MigratorStatus::fromString("NotMigrated"), + migration::MigratorStatus::Status::NotMigrated ); EXPECT_EQ( - migration::MigratorStatus::fromString("NotKnown"), migration::MigratorStatus::NotKnown + migration::MigratorStatus::fromString("NotKnown"), + migration::MigratorStatus::Status::NotKnown ); EXPECT_EQ( - migration::MigratorStatus::fromString("Unknown"), migration::MigratorStatus::NotMigrated + migration::MigratorStatus::fromString("Unknown"), + migration::MigratorStatus::Status::NotMigrated ); } TEST(MigratiorStatus, Compare) { - migration::MigratorStatus const status1(migration::MigratorStatus::Migrated); - migration::MigratorStatus status2(migration::MigratorStatus::Migrated); + migration::MigratorStatus const status1(migration::MigratorStatus::Status::Migrated); + migration::MigratorStatus status2(migration::MigratorStatus::Status::Migrated); EXPECT_TRUE(status1 == status2); - status2 = migration::MigratorStatus(migration::MigratorStatus::NotMigrated); + status2 = migration::MigratorStatus(migration::MigratorStatus::Status::NotMigrated); EXPECT_FALSE(status1 == status2); - EXPECT_FALSE(status1 == migration::MigratorStatus::NotMigrated); - EXPECT_TRUE(status1 == migration::MigratorStatus::Migrated); + EXPECT_FALSE(status1 == migration::MigratorStatus::Status::NotMigrated); + EXPECT_TRUE(status1 == migration::MigratorStatus::Status::Migrated); } diff --git a/tests/unit/rpc/RPCHelpersTests.cpp b/tests/unit/rpc/RPCHelpersTests.cpp index e00c13481..3b2fa2010 100644 --- a/tests/unit/rpc/RPCHelpersTests.cpp +++ b/tests/unit/rpc/RPCHelpersTests.cpp @@ -333,7 +333,7 @@ TEST_F(RPCHelpersTest, EncodeCTID) { auto const ctid = encodeCTID(0x1234, 0x67, 0x89); ASSERT_TRUE(ctid); - EXPECT_EQ(*ctid, "C000123400670089"); + EXPECT_EQ(*ctid, "C000123400670089"); // NOLINT(bugprone-unchecked-optional-access) EXPECT_FALSE(encodeCTID(0x1FFFFFFF, 0x67, 0x89)); } @@ -341,6 +341,7 @@ TEST_F(RPCHelpersTest, DecodeCTIDString) { auto const ctid = decodeCTID("C000123400670089"); ASSERT_TRUE(ctid); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(*ctid, std::make_tuple(0x1234, 0x67, 0x89)); EXPECT_FALSE(decodeCTID("F000123400670089")); EXPECT_FALSE(decodeCTID("F0001234006700")); @@ -352,6 +353,7 @@ TEST_F(RPCHelpersTest, DecodeCTIDInt) uint64_t ctidStr = 0xC000123400670089; auto const ctid = decodeCTID(ctidStr); ASSERT_TRUE(ctid); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(*ctid, std::make_tuple(0x1234, 0x67, 0x89)); ctidStr = 0xF000123400670089; EXPECT_FALSE(decodeCTID(ctidStr)); diff --git a/tests/unit/rpc/WorkQueueTests.cpp b/tests/unit/rpc/WorkQueueTests.cpp index 65d486c7a..64fde5703 100644 --- a/tests/unit/rpc/WorkQueueTests.cpp +++ b/tests/unit/rpc/WorkQueueTests.cpp @@ -144,7 +144,7 @@ TEST_F(WorkQueuePriorityTest, HighPriorityTasks) for (int i = 0; i < kTOTAL; ++i) { queue.postCoro( [&](auto) { - std::lock_guard const lock(mtx); + std::scoped_lock const lock(mtx); executionOrder.push_back(WorkQueue::Priority::High); }, /* isWhiteListed = */ true, @@ -152,7 +152,7 @@ TEST_F(WorkQueuePriorityTest, HighPriorityTasks) ); queue.postCoro( [&](auto) { - std::lock_guard const lock(mtx); + std::scoped_lock const lock(mtx); executionOrder.push_back(WorkQueue::Priority::Default); }, /* isWhiteListed = */ true, diff --git a/tests/unit/rpc/common/CheckersTests.cpp b/tests/unit/rpc/common/CheckersTests.cpp index 1bc02fbaa..2c34322cb 100644 --- a/tests/unit/rpc/common/CheckersTests.cpp +++ b/tests/unit/rpc/common/CheckersTests.cpp @@ -21,19 +21,22 @@ struct DeprecatedTests : ::testing::Test { TEST_F(DeprecatedTests, Field) { auto warning = Deprecated<>::check(json, "some_string"); - ASSERT_TRUE(warning); + ASSERT_TRUE(warning.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->warningCode, WarningCode::WarnRpcDeprecated); warning = Deprecated<>::check(json, "other"); - EXPECT_FALSE(warning); + EXPECT_FALSE(warning.has_value()); } TEST_F(DeprecatedTests, FieldWithStringValue) { Deprecated const checker{"some_value"}; auto warning = checker.check(json, "some_string"); - ASSERT_TRUE(warning); + ASSERT_TRUE(warning.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->warningCode, WarningCode::WarnRpcDeprecated); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->extraMessage, "Value 'some_value' for field 'some_string' is deprecated"); EXPECT_FALSE(Deprecated{"other"}.check(json, "some_string")); } @@ -42,8 +45,10 @@ TEST_F(DeprecatedTests, FieldWithIntValue) { Deprecated const checker{42}; auto warning = checker.check(json, "some_number"); - ASSERT_TRUE(warning); + ASSERT_TRUE(warning.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->warningCode, WarningCode::WarnRpcDeprecated); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->extraMessage, "Value '42' for field 'some_number' is deprecated"); EXPECT_FALSE(Deprecated{43}.check(json, "some_number")); } @@ -52,8 +57,10 @@ TEST_F(DeprecatedTests, FieldWithBoolValue) { Deprecated const checker{false}; auto warning = checker.check(json, "some_bool"); - ASSERT_TRUE(warning); + ASSERT_TRUE(warning.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->warningCode, WarningCode::WarnRpcDeprecated); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->extraMessage, "Value 'false' for field 'some_bool' is deprecated"); EXPECT_FALSE(Deprecated{true}.check(json, "some_bool")); } @@ -62,8 +69,10 @@ TEST_F(DeprecatedTests, FieldWithFloatValue) { Deprecated const checker{3.14}; auto warning = checker.check(json, "some_float"); - ASSERT_TRUE(warning); + ASSERT_TRUE(warning.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->warningCode, WarningCode::WarnRpcDeprecated); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(warning->extraMessage, "Value '3.14' for field 'some_float' is deprecated"); EXPECT_FALSE(Deprecated{3.15}.check(json, "some_float")); } diff --git a/tests/unit/rpc/common/SpecsTests.cpp b/tests/unit/rpc/common/SpecsTests.cpp index d0a8a421e..8e48db857 100644 --- a/tests/unit/rpc/common/SpecsTests.cpp +++ b/tests/unit/rpc/common/SpecsTests.cpp @@ -44,7 +44,7 @@ struct SpecsTests : testing::Test { { } - std::optional + [[nodiscard]] std::optional check(boost::json::value const& value, std::string key) const { return ref.check(value, key); @@ -100,8 +100,9 @@ INSTANTIATE_TEST_SUITE_P( TEST_P(FieldProcessorTests, FieldSpecWithRequirementProcess) { EXPECT_CALL(requirementMock, verify).WillOnce(testing::Return(GetParam().requirementResult)); - if (GetParam().otherRequirementResult) { + if (GetParam().otherRequirementResult.has_value()) { EXPECT_CALL(anotherRequirementMock, verify) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) .WillOnce(testing::Return(GetParam().otherRequirementResult.value())); } @@ -204,8 +205,9 @@ INSTANTIATE_TEST_SUITE_P( TEST_P(RpcSpecProcessTests, Process) { EXPECT_CALL(requirementMock, verify).WillOnce(testing::Return(GetParam().requirementResult)); - if (GetParam().otherRequirementResult) { + if (GetParam().otherRequirementResult.has_value()) { EXPECT_CALL(anotherRequirementMock, verify) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) .WillOnce(testing::Return(GetParam().otherRequirementResult.value())); } auto const result = spec.process(json); diff --git a/tests/unit/rpc/handlers/AccountChannelsTests.cpp b/tests/unit/rpc/handlers/AccountChannelsTests.cpp index db7e2204a..9a517199d 100644 --- a/tests/unit/rpc/handlers/AccountChannelsTests.cpp +++ b/tests/unit/rpc/handlers/AccountChannelsTests.cpp @@ -566,9 +566,9 @@ TEST_F(RPCAccountChannelsHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), 20); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 20); EXPECT_THAT( - boost::json::value_to((*output.result).as_object().at("marker")), + boost::json::value_to(output.result->as_object().at("marker")), EndsWith(",0") ); }); @@ -664,7 +664,7 @@ TEST_F(RPCAccountChannelsHandlerTest, UseDestination) auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), 20); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 20); }); } @@ -701,7 +701,7 @@ TEST_F(RPCAccountChannelsHandlerTest, EmptyChannel) auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), 0); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 0); }); } @@ -859,10 +859,10 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerOutput) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - boost::json::value_to((*output.result).as_object().at("marker")), + boost::json::value_to(output.result->as_object().at("marker")), fmt::format("{},{}", kINDEX1, kNEXT_PAGE) ); - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), 15); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 15); }); } @@ -920,10 +920,10 @@ TEST_F(RPCAccountChannelsHandlerTest, MarkerInput) auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_TRUE((*output.result).as_object().if_contains("marker") == nullptr); + EXPECT_TRUE(output.result->as_object().if_contains("marker") == nullptr); // the first item is the marker itself, so the result will have limit-1 // items - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), kLIMIT - 1); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), kLIMIT - 1); }); } @@ -972,9 +972,9 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitLessThanMin) auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), 2); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 2); EXPECT_EQ( - (*output.result).as_object().at("limit").as_uint64(), AccountChannelsHandler::kLIMIT_MIN + output.result->as_object().at("limit").as_uint64(), AccountChannelsHandler::kLIMIT_MIN ); }); } @@ -1024,9 +1024,9 @@ TEST_F(RPCAccountChannelsHandlerTest, LimitMoreThanMax) auto handler = AnyHandler{AccountChannelsHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("channels").as_array().size(), 2); + EXPECT_EQ(output.result->as_object().at("channels").as_array().size(), 2); EXPECT_EQ( - (*output.result).as_object().at("limit").as_uint64(), AccountChannelsHandler::kLIMIT_MAX + output.result->as_object().at("limit").as_uint64(), AccountChannelsHandler::kLIMIT_MAX ); }); } diff --git a/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp b/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp index 3c2797ccd..614d739ce 100644 --- a/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp +++ b/tests/unit/rpc/handlers/AccountCurrenciesTests.cpp @@ -305,7 +305,7 @@ TEST_F(RPCAccountCurrenciesHandlerTest, RequestViaLegderSeq) runSpawn([&](auto yield) { auto const output = handler.process(kINPUT, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("ledger_index").as_uint64(), ledgerSeq); + EXPECT_EQ(output.result->as_object().at("ledger_index").as_uint64(), ledgerSeq); }); } diff --git a/tests/unit/rpc/handlers/AccountLinesTests.cpp b/tests/unit/rpc/handlers/AccountLinesTests.cpp index 6202ade1a..f4fd6500f 100644 --- a/tests/unit/rpc/handlers/AccountLinesTests.cpp +++ b/tests/unit/rpc/handlers/AccountLinesTests.cpp @@ -610,9 +610,9 @@ TEST_F(RPCAccountLinesHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("lines").as_array().size(), 20); + EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), 20); EXPECT_THAT( - boost::json::value_to((*output.result).as_object().at("marker")), + boost::json::value_to(output.result->as_object().at("marker")), EndsWith(",0") ); }); @@ -710,7 +710,7 @@ TEST_F(RPCAccountLinesHandlerTest, UseDestination) auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("lines").as_array().size(), 20); + EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), 20); }); } @@ -747,7 +747,7 @@ TEST_F(RPCAccountLinesHandlerTest, EmptyChannel) auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("lines").as_array().size(), 0); + EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), 0); }); } @@ -1002,10 +1002,10 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerOutput) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - boost::json::value_to((*output.result).as_object().at("marker")), + boost::json::value_to(output.result->as_object().at("marker")), fmt::format("{},{}", kINDEX1, kNEXT_PAGE) ); - EXPECT_EQ((*output.result).as_object().at("lines").as_array().size(), 15); + EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), 15); }); } @@ -1064,10 +1064,10 @@ TEST_F(RPCAccountLinesHandlerTest, MarkerInput) auto handler = AnyHandler{AccountLinesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_TRUE((*output.result).as_object().if_contains("marker") == nullptr); + EXPECT_TRUE(output.result->as_object().if_contains("marker") == nullptr); // the first item is the marker itself, so the result will have limit-1 // items - EXPECT_EQ((*output.result).as_object().at("lines").as_array().size(), kLIMIT - 1); + EXPECT_EQ(output.result->as_object().at("lines").as_array().size(), kLIMIT - 1); }); } diff --git a/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp b/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp index f1f2c447d..1421c5086 100644 --- a/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp +++ b/tests/unit/rpc/handlers/AccountMPTokenIssuancesTests.cpp @@ -493,7 +493,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const resultJson = (*output.result).as_object(); + auto const resultJson = output.result->as_object(); EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLIMIT); ASSERT_TRUE(resultJson.contains("marker")); EXPECT_THAT(boost::json::value_to(resultJson.at("marker")), EndsWith(",0")); @@ -514,7 +514,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - (*output.result).as_object().at("limit").as_uint64(), + output.result->as_object().at("limit").as_uint64(), AccountMPTokenIssuancesHandler::kLIMIT_MIN ); }); @@ -534,7 +534,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - (*output.result).as_object().at("limit").as_uint64(), + output.result->as_object().at("limit").as_uint64(), AccountMPTokenIssuancesHandler::kLIMIT_MAX ); }); @@ -593,7 +593,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MarkerOutput) auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const& resultJson = (*output.result).as_object(); + auto const& resultJson = output.result->as_object(); EXPECT_EQ( boost::json::value_to(resultJson.at("marker")), fmt::format("{},{}", kISSUANCE_INDEX1, kNEXT_PAGE) @@ -652,7 +652,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, MarkerInput) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const& resultJson = (*output.result).as_object(); + auto const& resultJson = output.result->as_object(); EXPECT_TRUE(resultJson.if_contains("marker") == nullptr); EXPECT_EQ(resultJson.at("mpt_issuances").as_array().size(), kLIMIT - 1); }); @@ -861,7 +861,7 @@ TEST_F(RPCAccountMPTokenIssuancesHandlerTest, EmptyResult) auto const handler = AnyHandler{AccountMPTokenIssuancesHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("mpt_issuances").as_array().size(), 0); + EXPECT_EQ(output.result->as_object().at("mpt_issuances").as_array().size(), 0); }); } @@ -1069,7 +1069,7 @@ TEST_P(AccountMPTokenIssuancesImmutableFlagsTest, SingleFlag) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const& resultJson = (*output.result).as_object(); + auto const& resultJson = output.result->as_object(); auto const& issuances = resultJson.at("mpt_issuances").as_array(); ASSERT_EQ(issuances.size(), 1); @@ -1175,7 +1175,7 @@ TEST_P(AccountMPTokenIssuancesMutableFlagsTest, SingleMutableFlag) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const& resultJson = (*output.result).as_object(); + auto const& resultJson = output.result->as_object(); auto const& issuances = resultJson.at("mpt_issuances").as_array(); ASSERT_EQ(issuances.size(), 1); diff --git a/tests/unit/rpc/handlers/AccountMPTokensTests.cpp b/tests/unit/rpc/handlers/AccountMPTokensTests.cpp index 6426a52cb..eb9e19955 100644 --- a/tests/unit/rpc/handlers/AccountMPTokensTests.cpp +++ b/tests/unit/rpc/handlers/AccountMPTokensTests.cpp @@ -450,7 +450,7 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const resultJson = (*output.result).as_object(); + auto const resultJson = output.result->as_object(); EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLIMIT); ASSERT_TRUE(resultJson.contains("marker")); EXPECT_THAT(boost::json::value_to(resultJson.at("marker")), EndsWith(",0")); @@ -472,7 +472,7 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - (*output.result).as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLIMIT_MIN + output.result->as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLIMIT_MIN ); }); @@ -492,7 +492,7 @@ TEST_F(RPCAccountMPTokensHandlerTest, UseLimit) auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); EXPECT_EQ( - (*output.result).as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLIMIT_MAX + output.result->as_object().at("limit").as_uint64(), AccountMPTokensHandler::kLIMIT_MAX ); }); } @@ -556,7 +556,7 @@ TEST_F(RPCAccountMPTokensHandlerTest, MarkerOutput) auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const& resultJson = (*output.result).as_object(); + auto const& resultJson = output.result->as_object(); EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLIMIT); EXPECT_EQ( boost::json::value_to(resultJson.at("marker")), @@ -618,7 +618,7 @@ TEST_F(RPCAccountMPTokensHandlerTest, MarkerInput) auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - auto const& resultJson = (*output.result).as_object(); + auto const& resultJson = output.result->as_object(); EXPECT_TRUE(resultJson.if_contains("marker") == nullptr); EXPECT_EQ(resultJson.at("mptokens").as_array().size(), kLIMIT - 1); }); @@ -809,6 +809,6 @@ TEST_F(RPCAccountMPTokensHandlerTest, EmptyResult) auto const handler = AnyHandler{AccountMPTokensHandler{this->backend_}}; auto const output = handler.process(input, Context{yield}); ASSERT_TRUE(output); - EXPECT_EQ((*output.result).as_object().at("mptokens").as_array().size(), 0); + EXPECT_EQ(output.result->as_object().at("mptokens").as_array().size(), 0); }); } diff --git a/tests/unit/rpc/handlers/CredentialHelpersTests.cpp b/tests/unit/rpc/handlers/CredentialHelpersTests.cpp index 4eb871a96..9a90974fc 100644 --- a/tests/unit/rpc/handlers/CredentialHelpersTests.cpp +++ b/tests/unit/rpc/handlers/CredentialHelpersTests.cpp @@ -83,12 +83,13 @@ TEST(ParseAuthorizeCredentialsTest, ValidCredentialsArray) ASSERT_TRUE(cred.isFieldPresent(ripple::sfIssuer)); ASSERT_TRUE(cred.isFieldPresent(ripple::sfCredentialType)); - auto const expectedIssuer = *ripple::parseBase58( - static_cast(credential1[JS(issuer)].as_string()) - ); + auto const expectedIssuer = + *ripple::parseBase58( // NOLINT(bugprone-unchecked-optional-access) + static_cast(credential1[JS(issuer)].as_string()) + ); auto const expectedCredentialType = - ripple::strUnHex(static_cast(credential1[JS(credential_type)].as_string())) - .value(); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *ripple::strUnHex(static_cast(credential1[JS(credential_type)].as_string())); EXPECT_EQ(cred.getAccountID(ripple::sfIssuer), expectedIssuer); EXPECT_EQ(cred.getFieldVL(ripple::sfCredentialType), expectedCredentialType); diff --git a/tests/unit/rpc/handlers/LedgerEntryTests.cpp b/tests/unit/rpc/handlers/LedgerEntryTests.cpp index 9cdefcb47..9598266d1 100644 --- a/tests/unit/rpc/handlers/LedgerEntryTests.cpp +++ b/tests/unit/rpc/handlers/LedgerEntryTests.cpp @@ -2832,7 +2832,9 @@ generateTestValuesForNormalPathTest() account1, account2, ripple::Slice( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) ripple::strUnHex(kCREDENTIAL_TYPE)->data(), + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) ripple::strUnHex(kCREDENTIAL_TYPE)->size() ) ) @@ -3224,11 +3226,12 @@ generateTestValuesForNormalPathTest() kACCOUNT, kRANGE_MAX ), - .expectedIndex = - ripple::keylet::permissionedDomain( - ripple::parseBase58(kACCOUNT).value(), kRANGE_MAX - ) - .key, + .expectedIndex = ripple::keylet::permissionedDomain( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *ripple::parseBase58(kACCOUNT), + kRANGE_MAX + ) + .key, .mockedEntity = createPermissionedDomainObject( kACCOUNT, kINDEX1, kRANGE_MAX, 0, ripple::uint256{0}, 0 ) @@ -3269,10 +3272,9 @@ generateTestValuesForNormalPathTest() kRANGE_MAX ), .expectedIndex = - ripple::keylet::vault( - ripple::parseBase58(kACCOUNT).value(), kRANGE_MAX - ) - .key, + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::vault(*ripple::parseBase58(kACCOUNT), kRANGE_MAX) + .key, .mockedEntity = createVault( kACCOUNT, kACCOUNT, @@ -3312,11 +3314,12 @@ generateTestValuesForNormalPathTest() kACCOUNT, kRANGE_MAX ), - .expectedIndex = - ripple::keylet::loanbroker( - ripple::parseBase58(kACCOUNT).value(), kRANGE_MAX - ) - .key, + .expectedIndex = ripple::keylet::loanbroker( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *ripple::parseBase58(kACCOUNT), + kRANGE_MAX + ) + .key, .mockedEntity = createLoanBroker( kACCOUNT, kACCOUNT, kRANGE_MAX, ripple::uint256{kINDEX1}, 1, ripple::uint256{0}, 0 ) @@ -3498,8 +3501,8 @@ TEST_F(RPCLedgerEntryTest, Vault_BinaryFalse) ); auto const vaultKey = - ripple::keylet::vault(ripple::parseBase58(kACCOUNT).value(), kRANGE_MAX) - .key; + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ripple::keylet::vault(*ripple::parseBase58(kACCOUNT), kRANGE_MAX).key; ripple::STLedgerEntry const sle{ ripple::SerialIter{ @@ -3546,11 +3549,12 @@ TEST_F(RPCLedgerEntryTest, LoanBroker_BinaryFalse) kACCOUNT, kACCOUNT, kRANGE_MAX, ripple::uint256{kINDEX1}, 1, ripple::uint256{1}, 0 ); - auto const loanBrokerKey = - ripple::keylet::loanbroker( - ripple::parseBase58(kACCOUNT).value(), kRANGE_MAX - ) - .key; + auto const loanBrokerKey = ripple::keylet::loanbroker( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *ripple::parseBase58(kACCOUNT), + kRANGE_MAX + ) + .key; ripple::STLedgerEntry const sle{ ripple::SerialIter{ diff --git a/tests/unit/rpc/handlers/ServerInfoTests.cpp b/tests/unit/rpc/handlers/ServerInfoTests.cpp index 7deeab8f9..c35e5a4cb 100644 --- a/tests/unit/rpc/handlers/ServerInfoTests.cpp +++ b/tests/unit/rpc/handlers/ServerInfoTests.cpp @@ -166,8 +166,8 @@ TEST_F(RPCServerInfoHandlerTest, NoFeesErrorsOutWithInternal) TEST_F(RPCServerInfoHandlerTest, DefaultOutputIsPresent) { MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); @@ -209,8 +209,8 @@ TEST_F(RPCServerInfoHandlerTest, DefaultOutputIsPresent) TEST_F(RPCServerInfoHandlerTest, AmendmentBlockedIsPresentIfSet) { MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); @@ -250,8 +250,8 @@ TEST_F(RPCServerInfoHandlerTest, AmendmentBlockedIsPresentIfSet) TEST_F(RPCServerInfoHandlerTest, CorruptionDetectedIsPresentIfSet) { MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).WillOnce(Return(ledgerHeader)); @@ -291,7 +291,7 @@ TEST_F(RPCServerInfoHandlerTest, CorruptionDetectedIsPresentIfSet) TEST_F(RPCServerInfoHandlerTest, CacheReportsEnabledFlagCorrectly) { MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old EXPECT_CALL(*backend_, fetchLedgerBySequence).Times(2).WillRepeatedly(Return(ledgerHeader)); @@ -346,9 +346,9 @@ TEST_F(RPCServerInfoHandlerTest, CacheReportsEnabledFlagCorrectly) TEST_F(RPCServerInfoHandlerTest, AdminSectionPresentWhenAdminFlagIsSet) { - MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockLoadBalancer const* rawBalancerPtr = mockLoadBalancerPtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const empty = json::object{}; auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old @@ -389,9 +389,9 @@ TEST_F(RPCServerInfoHandlerTest, AdminSectionPresentWhenAdminFlagIsSet) TEST_F(RPCServerInfoHandlerTest, BackendCountersPresentWhenRequestWithParam) { - MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockLoadBalancer const* rawBalancerPtr = mockLoadBalancerPtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const empty = json::object{}; auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old @@ -439,9 +439,9 @@ TEST_F(RPCServerInfoHandlerTest, BackendCountersPresentWhenRequestWithParam) TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesPresent) { - MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockLoadBalancer const* rawBalancerPtr = mockLoadBalancerPtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const empty = json::object{}; auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old @@ -493,9 +493,9 @@ TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesPresent) TEST_F(RPCServerInfoHandlerTest, RippledForwardedValuesMissingNoExceptionThrown) { - MockLoadBalancer* rawBalancerPtr = mockLoadBalancerPtr_.get(); - MockCounters* rawCountersPtr = mockCountersPtr_.get(); - MockETLService* rawETLServicePtr = mockETLServicePtr_.get(); + MockLoadBalancer const* rawBalancerPtr = mockLoadBalancerPtr_.get(); + MockCounters const* rawCountersPtr = mockCountersPtr_.get(); + MockETLService const* rawETLServicePtr = mockETLServicePtr_.get(); auto const empty = json::object{}; auto const ledgerHeader = createLedgerHeader(kLEDGER_HASH, 30, 3); // 3 seconds old diff --git a/tests/unit/rpc/handlers/UnsubscribeTests.cpp b/tests/unit/rpc/handlers/UnsubscribeTests.cpp index 46c94ff5d..281b75079 100644 --- a/tests/unit/rpc/handlers/UnsubscribeTests.cpp +++ b/tests/unit/rpc/handlers/UnsubscribeTests.cpp @@ -548,12 +548,14 @@ TEST_F(RPCUnsubscribeTest, Accounts) EXPECT_CALL( *mockSubscriptionManagerPtr_, - unsubAccount(rpc::accountFromStringStrict(kACCOUNT).value(), _) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + unsubAccount(*rpc::accountFromStringStrict(kACCOUNT), _) ) .Times(1); EXPECT_CALL( *mockSubscriptionManagerPtr_, - unsubAccount(rpc::accountFromStringStrict(kACCOUNT2).value(), _) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + unsubAccount(*rpc::accountFromStringStrict(kACCOUNT2), _) ) .Times(1); @@ -579,12 +581,14 @@ TEST_F(RPCUnsubscribeTest, AccountsProposed) EXPECT_CALL( *mockSubscriptionManagerPtr_, - unsubProposedAccount(rpc::accountFromStringStrict(kACCOUNT).value(), _) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + unsubProposedAccount(*rpc::accountFromStringStrict(kACCOUNT), _) ) .Times(1); EXPECT_CALL( *mockSubscriptionManagerPtr_, - unsubProposedAccount(rpc::accountFromStringStrict(kACCOUNT2).value(), _) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + unsubProposedAccount(*rpc::accountFromStringStrict(kACCOUNT2), _) ) .Times(1); @@ -620,7 +624,7 @@ TEST_F(RPCUnsubscribeTest, Books) auto const parsedBookMaybe = rpc::parseBook(input.as_object().at("books").as_array()[0].as_object()); - auto const book = parsedBookMaybe.value(); + auto const book = *parsedBookMaybe; EXPECT_CALL(*mockSubscriptionManagerPtr_, unsubBook(book, _)).Times(1); EXPECT_CALL(*mockSubscriptionManagerPtr_, unsubBook(ripple::reversed(book), _)).Times(1); @@ -656,7 +660,7 @@ TEST_F(RPCUnsubscribeTest, SingleBooks) auto const parsedBookMaybe = rpc::parseBook(input.as_object().at("books").as_array()[0].as_object()); - auto const book = parsedBookMaybe.value(); + auto const book = *parsedBookMaybe; EXPECT_CALL(*mockSubscriptionManagerPtr_, unsubBook(book, _)).Times(1); diff --git a/tests/unit/util/ChannelTests.cpp b/tests/unit/util/ChannelTests.cpp index a057439d3..14380fcaf 100644 --- a/tests/unit/util/ChannelTests.cpp +++ b/tests/unit/util/ChannelTests.cpp @@ -484,7 +484,7 @@ TEST_P(ChannelCallbackTest, ChannelClosureScenarios) boost::asio::post( executor, [&executor, receiverPtr, senderPtr, &testCompleted]() { - senderPtr->reset(); + (*senderPtr).reset(); EXPECT_TRUE(receiverPtr->isClosed()); boost::asio::post(executor, [receiverPtr, &testCompleted]() { @@ -555,7 +555,7 @@ TEST_P(ChannelCallbackTest, TryMethodsWithClosedChannel) EXPECT_TRUE(senderPtr->value().trySend(100)); EXPECT_TRUE(senderPtr->value().trySend(101)); - senderPtr->reset(); + (*senderPtr).reset(); EXPECT_TRUE(receiverPtr->isClosed()); diff --git a/tests/unit/util/ObservableValueAtomicTest.cpp b/tests/unit/util/ObservableValueAtomicTest.cpp index 4822df35d..4837fb4ae 100644 --- a/tests/unit/util/ObservableValueAtomicTest.cpp +++ b/tests/unit/util/ObservableValueAtomicTest.cpp @@ -153,7 +153,7 @@ TEST_F(ObservableValueAtomicTest, ThreadSafetyBasic) auto connection = obs.observe([&](int const& value) { notificationCount.fetch_add(1); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); values.push_back(value); }); @@ -181,7 +181,7 @@ TEST_F(ObservableValueAtomicTest, ThreadSafetyBasic) EXPECT_GT(obs.get(), 0); EXPECT_GT(notificationCount.load(), 0); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); for (auto const& value : values) { EXPECT_GT(value, 0); } @@ -258,7 +258,7 @@ TEST_F(ObservableValueAtomicTest, RaceConditionNotificationIntegrity) auto connection = obs.observe([&](int const& value) { notificationCount.fetch_add(1); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); values.push_back(value); }); @@ -282,7 +282,7 @@ TEST_F(ObservableValueAtomicTest, RaceConditionNotificationIntegrity) EXPECT_GT(notificationCount.load(), 0); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); for (auto const& value : values) { EXPECT_GE(value, 0); EXPECT_LE(value, 2); @@ -302,7 +302,7 @@ TEST_F(ObservableValueAtomicTest, DeterministicNotificationTest) auto connection = obs.observe([&](int const& value) { notificationCount.fetch_add(1); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); values.push_back(value); }); @@ -321,7 +321,7 @@ TEST_F(ObservableValueAtomicTest, DeterministicNotificationTest) // Each thread sets a unique value, so expect exactly kNumThreads notifications EXPECT_EQ(notificationCount.load(), kNUM_THREADS); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); EXPECT_EQ(values.size(), kNUM_THREADS); for (auto const& value : values) { @@ -366,7 +366,7 @@ TEST_F(ObservableValueAtomicTest, AtomicRaceConditionCorrectness) auto connection = obs.observe([&](int const& value) { notificationCount.fetch_add(1); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); values.push_back(value); }); @@ -392,7 +392,7 @@ TEST_F(ObservableValueAtomicTest, AtomicRaceConditionCorrectness) // but at least one per thread since they use unique base values EXPECT_GE(notificationCount.load(), kNUM_THREADS); - std::lock_guard const lock(valuesMutex); + std::scoped_lock const lock(valuesMutex); EXPECT_GE(values.size(), kNUM_THREADS); for (auto const& value : values) diff --git a/tests/unit/util/ResponseExpirationCacheTests.cpp b/tests/unit/util/ResponseExpirationCacheTests.cpp index e4a430bf3..23a187574 100644 --- a/tests/unit/util/ResponseExpirationCacheTests.cpp +++ b/tests/unit/util/ResponseExpirationCacheTests.cpp @@ -21,7 +21,7 @@ TEST_F(ResponseExpirationCacheTests, PutAndGetNotExpired) cache_.put("key", object_); auto result = cache_.get("key"); ASSERT_TRUE(result.has_value()); - EXPECT_EQ(*result, object_); + EXPECT_EQ(*result, object_); // NOLINT(bugprone-unchecked-optional-access) result = cache_.get("key2"); ASSERT_FALSE(result.has_value()); diff --git a/tests/unit/util/TimeUtilsTests.cpp b/tests/unit/util/TimeUtilsTests.cpp index 3f8415c1a..18b65cf7c 100644 --- a/tests/unit/util/TimeUtilsTests.cpp +++ b/tests/unit/util/TimeUtilsTests.cpp @@ -11,6 +11,7 @@ TEST(TimeUtilTests, SystemTpFromUTCStrSuccess) { auto const tp = util::systemTpFromUtcStr("2024-01-01T10:50:40Z", "%Y-%m-%dT%H:%M:%SZ"); ASSERT_TRUE(tp.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) auto const time = std::chrono::system_clock::to_time_t(tp.value()); std::tm timeStruct{}; gmtime_r(&time, &timeStruct); @@ -55,6 +56,7 @@ TEST(TimeUtilTests, StringToTimePointToString) auto timePoint = util::systemTpFromUtcStr(originalStr, isoFormat); ASSERT_TRUE(timePoint.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) std::string const convertedStr = util::systemTpToUtcStr(*timePoint, isoFormat); EXPECT_EQ(originalStr, convertedStr); @@ -63,10 +65,11 @@ TEST(TimeUtilTests, StringToTimePointToString) auto timePoint2 = util::systemTpFromUtcStr(originalCustomStr, customFormat); ASSERT_TRUE(timePoint2.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) std::string const convertedCustomStr = util::systemTpToUtcStr(*timePoint2, customFormat); EXPECT_EQ(originalCustomStr, convertedCustomStr); - EXPECT_EQ(*timePoint, *timePoint2); + EXPECT_EQ(*timePoint, *timePoint2); // NOLINT(bugprone-unchecked-optional-access) } TEST(TimeUtilTests, SystemTpFromLedgerCloseTime) diff --git a/tests/unit/util/async/AnyStopTokenTests.cpp b/tests/unit/util/async/AnyStopTokenTests.cpp index 43cd0c5f7..ffb5dab5c 100644 --- a/tests/unit/util/async/AnyStopTokenTests.cpp +++ b/tests/unit/util/async/AnyStopTokenTests.cpp @@ -11,7 +11,7 @@ namespace { struct FakeStopToken { bool stopRequested = false; - bool + [[nodiscard]] bool isStopRequested() const { return stopRequested; diff --git a/tests/unit/util/async/AsyncExecutionContextTests.cpp b/tests/unit/util/async/AsyncExecutionContextTests.cpp index b284edcb0..e54f76aec 100644 --- a/tests/unit/util/async/AsyncExecutionContextTests.cpp +++ b/tests/unit/util/async/AsyncExecutionContextTests.cpp @@ -402,7 +402,7 @@ TYPED_TEST(AsyncExecutionContextTests, repeatingOperationAutoAborts) { auto const repeatDelay = std::chrono::milliseconds{1}; auto const timeout = std::chrono::milliseconds{15}; - auto callCount = 0uz; + std::atomic_size_t callCount = 0uz; auto timeSpentMs = 0u; { @@ -420,8 +420,8 @@ TYPED_TEST(AsyncExecutionContextTests, repeatingOperationAutoAborts) EXPECT_GE(callCount, expectedPureCalls / 2u); // expect at least half of the scheduled calls EXPECT_LE( - callCount, expectedActualCount - ); // never should be called more times than possible before timeout + callCount, expectedActualCount + 1u + ); // at most 1 extra call from an in-flight post that raced with abort } using NoErrorHandlerSyncExecutionContext = BasicExecutionContext< diff --git a/tests/unit/util/config/ClioConfigDefinitionTests.cpp b/tests/unit/util/config/ClioConfigDefinitionTests.cpp index cd3d841ae..f57814820 100644 --- a/tests/unit/util/config/ClioConfigDefinitionTests.cpp +++ b/tests/unit/util/config/ClioConfigDefinitionTests.cpp @@ -311,7 +311,7 @@ TEST_F(IncorrectOverrideValues, InvalidJsonErrors) }; std::set actualErrors; - for (auto const& error : errors.value()) { + for (auto const& error : *errors) { // NOLINT(bugprone-unchecked-optional-access) actualErrors.insert(error.error); } EXPECT_EQ(expectedErrors, actualErrors); @@ -435,8 +435,10 @@ TEST_F(ClioConfigDefinitionParseArrayTest, missingRequiredFields) auto const configFile = ConfigFileJson{configJson}; auto const result = config.parse(configFile); ASSERT_TRUE(result.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(result->size(), 1); EXPECT_THAT(result->at(0).error, testing::StartsWith("The value of array.[].int")); + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(ClioConfigDefinitionParseArrayTest, missingAllRequiredFields) @@ -452,8 +454,10 @@ TEST_F(ClioConfigDefinitionParseArrayTest, missingAllRequiredFields) auto const configFile = ConfigFileJson{configJson}; auto const result = config.parse(configFile); ASSERT_TRUE(result.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(result->size(), 1); EXPECT_THAT(result->at(0).error, testing::StartsWith("The value of array.[].int")); + // NOLINTEND(bugprone-unchecked-optional-access) } TEST(ClioConfigDefinitionParse, unexpectedFields) @@ -478,14 +482,19 @@ TEST(ClioConfigDefinitionParse, unexpectedFields) auto const configFile = ConfigFileJson{configJson}; auto result = config.parse(configFile); - std::ranges::sort(*result, [](auto const& lhs, auto const& rhs) { - return lhs.error < rhs.error; - }); ASSERT_TRUE(result.has_value()); + std::ranges::sort( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + *result, + [](auto const& lhs, auto const& rhs) { return lhs.error < rhs.error; } + ); + ASSERT_TRUE(result.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) ASSERT_EQ(result->size(), 4); EXPECT_EQ(result->at(0).error, "Unknown key: unexpected_empty_array.[]"); EXPECT_EQ(result->at(1).error, "Unknown key: unexpected_non_empty_array.[].string"); EXPECT_EQ(result->at(2).error, "Unknown key: unexpected_object.string"); EXPECT_EQ(result->at(3).error, "Unknown key: unexpected_string"); + // NOLINTEND(bugprone-unchecked-optional-access) } diff --git a/tests/unit/util/config/ConfigFileJsonTests.cpp b/tests/unit/util/config/ConfigFileJsonTests.cpp index 56ec96148..973f38ddf 100644 --- a/tests/unit/util/config/ConfigFileJsonTests.cpp +++ b/tests/unit/util/config/ConfigFileJsonTests.cpp @@ -367,26 +367,28 @@ TEST_F(ConfigFileJsonTest, getArray) auto const array = jsonFileObj.getArray("array.[]"); ASSERT_EQ(array.size(), 4); - auto const value0 = array.at(0).value(); + auto const value0 = (*array.at(0)); // NOLINT(bugprone-unchecked-optional-access) ASSERT_TRUE(std::holds_alternative(value0)); EXPECT_EQ(std::get(value0), 1); - auto const value1 = array.at(1).value(); + auto const value1 = (*array.at(1)); // NOLINT(bugprone-unchecked-optional-access) ASSERT_TRUE(std::holds_alternative(value1)); EXPECT_EQ(std::get(value1), "2"); - auto const value2 = array.at(2).value(); + auto const value2 = (*array.at(2)); // NOLINT(bugprone-unchecked-optional-access) ASSERT_TRUE(std::holds_alternative(value2)); EXPECT_NEAR(std::get(value2), 3.14, kEPS); - auto const value3 = array.at(3).value(); + auto const value3 = (*array.at(3)); // NOLINT(bugprone-unchecked-optional-access) ASSERT_TRUE(std::holds_alternative(value3)); EXPECT_EQ(std::get(value3), true); auto const arrayFromObject = jsonFileObj.getArray("object.array.[]"); ASSERT_EQ(arrayFromObject.size(), 2); - EXPECT_EQ(std::get(arrayFromObject.at(0).value()), 3); - EXPECT_EQ(std::get(arrayFromObject.at(1).value()), 4); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(std::get((*arrayFromObject.at(0))), 3); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(std::get((*arrayFromObject.at(1))), 4); } TEST_F(ConfigFileJsonTest, getArrayObjectInArray) @@ -401,15 +403,19 @@ TEST_F(ConfigFileJsonTest, getArrayObjectInArray) auto const ints = jsonFileObj.getArray("array.[].int"); ASSERT_EQ(ints.size(), 2); - ASSERT_TRUE(std::holds_alternative(ints.at(0).value())); - EXPECT_EQ(std::get(ints.at(0).value()), 42); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ASSERT_TRUE(std::holds_alternative((*ints.at(0)))); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(std::get((*ints.at(0))), 42); EXPECT_FALSE(ints.at(1).has_value()); auto const strings = jsonFileObj.getArray("array.[].string"); ASSERT_EQ(strings.size(), 2); EXPECT_FALSE(strings.at(0).has_value()); - ASSERT_TRUE(std::holds_alternative(strings.at(1).value())); - EXPECT_EQ(std::get(strings.at(1).value()), "some string"); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + ASSERT_TRUE(std::holds_alternative((*strings.at(1)))); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(std::get((*strings.at(1))), "some string"); } TEST_F(ConfigFileJsonTest, getArrayOptionalInArray) @@ -424,16 +430,18 @@ TEST_F(ConfigFileJsonTest, getArrayOptionalInArray) auto const ints = jsonFileObj.getArray("array.[].int"); ASSERT_EQ(ints.size(), 2); - ASSERT_TRUE(std::holds_alternative(ints.at(0).value())); - EXPECT_EQ(std::get(ints.at(0).value()), 42); - ASSERT_TRUE(std::holds_alternative(ints.at(1).value())); - EXPECT_EQ(std::get(ints.at(1).value()), 24); + // NOLINTBEGIN(bugprone-unchecked-optional-access) + ASSERT_TRUE(std::holds_alternative((*ints.at(0)))); + EXPECT_EQ(std::get((*ints.at(0))), 42); + ASSERT_TRUE(std::holds_alternative((*ints.at(1)))); + EXPECT_EQ(std::get((*ints.at(1))), 24); auto const bools = jsonFileObj.getArray("array.[].bool"); ASSERT_EQ(bools.size(), 2); EXPECT_FALSE(bools.at(0).has_value()); - ASSERT_TRUE(std::holds_alternative(bools.at(1).value())); - EXPECT_EQ(std::get(bools.at(1).value()), true); + ASSERT_TRUE(std::holds_alternative((*bools.at(1)))); + EXPECT_EQ(std::get((*bools.at(1))), true); + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(ConfigFileJsonAssertTest, getArrayInvalidKey) diff --git a/tests/unit/util/config/ConfigValueTests.cpp b/tests/unit/util/config/ConfigValueTests.cpp index 634d108a8..797097501 100644 --- a/tests/unit/util/config/ConfigValueTests.cpp +++ b/tests/unit/util/config/ConfigValueTests.cpp @@ -100,7 +100,7 @@ TEST_F(ConfigValueConstraintTest, setValueWithConstraintTypeCheckError) EXPECT_CALL(constraint, checkTypeImpl).WillOnce(testing::Return(Error{"type error"})); auto const err = cv.setValue(value); EXPECT_TRUE(err.has_value()); - EXPECT_EQ(err->error, "Unknown_key type error"); + EXPECT_EQ(err->error, "Unknown_key type error"); // NOLINT(bugprone-unchecked-optional-access) } TEST_F(ConfigValueConstraintTest, defaultValueWithConstraint) @@ -135,18 +135,22 @@ TEST_F(ConstraintTest, SetValuesOnPortConstraint) { auto cvPort = ConfigValue{ConfigType::Integer}.defaultValue(4444).withConstraint(gValidatePort); auto const err = cvPort.setValue(99999); - EXPECT_TRUE(err.has_value()); + ASSERT_TRUE(err.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(err->error, "Unknown_key Port does not satisfy the constraint bounds"); EXPECT_TRUE(cvPort.setValue(33.33).has_value()); EXPECT_EQ( - cvPort.setValue(33.33).value().error, "Unknown_key value does not match type integer" + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + cvPort.setValue(33.33)->error, + "Unknown_key value does not match type integer" ); EXPECT_FALSE(cvPort.setValue(1).has_value()); auto cvPort2 = ConfigValue{ConfigType::String}.defaultValue("4444").withConstraint(gValidatePort); auto const strPortError = cvPort2.setValue("100000"); - EXPECT_TRUE(strPortError.has_value()); + ASSERT_TRUE(strPortError.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(strPortError->error, "Unknown_key Port does not satisfy the constraint bounds"); } @@ -156,17 +160,22 @@ TEST_F(ConstraintTest, OneOfConstraintOneValue) auto const databaseConstraint{OneOf{"database.type", arr}}; EXPECT_FALSE(databaseConstraint.checkConstraint("tracer").has_value()); - EXPECT_TRUE(databaseConstraint.checkConstraint(345).has_value()); - EXPECT_EQ( - databaseConstraint.checkConstraint(345)->error, - R"(Key "database.type"'s value must be a string)" - ); + { + auto const res = databaseConstraint.checkConstraint(345); + ASSERT_TRUE(res.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(res->error, R"(Key "database.type"'s value must be a string)"); + } - EXPECT_TRUE(databaseConstraint.checkConstraint("123.44").has_value()); - EXPECT_EQ( - databaseConstraint.checkConstraint("123.44")->error, - R"(You provided value "123.44". Key "database.type"'s value must be one of the following: tracer)" - ); + { + auto const res = databaseConstraint.checkConstraint("123.44"); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + res->error, + R"(You provided value "123.44". Key "database.type"'s value must be one of the following: tracer)" + ); + } } TEST_F(ConstraintTest, OneOfConstraint) @@ -176,14 +185,22 @@ TEST_F(ConstraintTest, OneOfConstraint) EXPECT_FALSE(oneOfCons.checkConstraint("trace").has_value()); - EXPECT_TRUE(oneOfCons.checkConstraint(345).has_value()); - EXPECT_EQ(oneOfCons.checkConstraint(345)->error, R"(Key "log.level"'s value must be a string)"); + { + auto const res = oneOfCons.checkConstraint(345); + ASSERT_TRUE(res.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(res->error, R"(Key "log.level"'s value must be a string)"); + } - EXPECT_TRUE(oneOfCons.checkConstraint("PETER_WAS_HERE").has_value()); - EXPECT_EQ( - oneOfCons.checkConstraint("PETER_WAS_HERE")->error, - R"(You provided value "PETER_WAS_HERE". Key "log.level"'s value must be one of the following: 123, trace, haha)" - ); + { + auto const res = oneOfCons.checkConstraint("PETER_WAS_HERE"); + ASSERT_TRUE(res.has_value()); + EXPECT_EQ( + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + res->error, + R"(You provided value "PETER_WAS_HERE". Key "log.level"'s value must be one of the following: 123, trace, haha)" + ); + } } TEST_F(ConstraintTest, IpConstraint) @@ -205,6 +222,7 @@ TEST_F(ConstraintTest, IpConstraint) auto const err = ip.setValue("extra$@symbols"); ASSERT_TRUE(err.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(err->error, "Unknown_key Ip is not a valid ip address or hostname"); } @@ -214,13 +232,19 @@ TEST_F(ConstraintTest, positiveNumConstraint) EXPECT_FALSE(numCons.checkConstraint(0)); EXPECT_FALSE(numCons.checkConstraint(5)); - EXPECT_TRUE(numCons.checkConstraint(true)); - EXPECT_EQ(numCons.checkConstraint(true)->error, fmt::format("Number must be of type integer")); + { + auto const res = numCons.checkConstraint(true); + ASSERT_TRUE(res.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(res->error, fmt::format("Number must be of type integer")); + } - EXPECT_TRUE(numCons.checkConstraint(8)); - EXPECT_EQ( - numCons.checkConstraint(8)->error, fmt::format("Number must be between {} and {}", 0, 5) - ); + { + auto const res = numCons.checkConstraint(8); + ASSERT_TRUE(res.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(res->error, fmt::format("Number must be between {} and {}", 0, 5)); + } } TEST_F(ConstraintTest, SetValuesOnNumberConstraint) @@ -228,7 +252,8 @@ TEST_F(ConstraintTest, SetValuesOnNumberConstraint) auto positiveNum = ConfigValue{ConfigType::Integer}.defaultValue(20u).withConstraint(gValidateUint16); auto const err = positiveNum.setValue(-22, "key"); - EXPECT_TRUE(err.has_value()); + ASSERT_TRUE(err.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(err->error, fmt::format("key Number must be between {} and {}", 1, 65535)); EXPECT_FALSE(positiveNum.setValue(99, "key")); } @@ -239,13 +264,20 @@ TEST_F(ConstraintTest, PositiveDoubleConstraint) EXPECT_FALSE(doubleCons.checkConstraint(0.2)); EXPECT_FALSE(doubleCons.checkConstraint(5.54)); EXPECT_FALSE(doubleCons.checkConstraint(3)); - EXPECT_TRUE(doubleCons.checkConstraint("-5")); - EXPECT_EQ( - doubleCons.checkConstraint("-5")->error, "Double number must be of type int or double" - ); - EXPECT_EQ( - doubleCons.checkConstraint(-5.6)->error, "Double number must be greater than or equal to 0" - ); + { + auto const res = doubleCons.checkConstraint("-5"); + ASSERT_TRUE(res.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(res->error, "Double number must be of type int or double"); + } + + { + auto const res = doubleCons.checkConstraint(-5.6); + ASSERT_TRUE(res.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + EXPECT_EQ(res->error, "Double number must be greater than or equal to 0"); + } + EXPECT_FALSE(doubleCons.checkConstraint(12.1)); } diff --git a/tests/unit/util/config/ValueViewTests.cpp b/tests/unit/util/config/ValueViewTests.cpp index ba93df7dc..a28c0c987 100644 --- a/tests/unit/util/config/ValueViewTests.cpp +++ b/tests/unit/util/config/ValueViewTests.cpp @@ -82,8 +82,8 @@ TEST_F(ValueViewTest, OptionalValues) ValueView const vv3{cv3}; ValueView const vv4{cv4}; - EXPECT_EQ(vv.asOptional().value(), 432); - EXPECT_EQ(vv.asOptional().value(), 432); + EXPECT_EQ(*vv.asOptional(), 432); // NOLINT(bugprone-unchecked-optional-access) + EXPECT_EQ(*vv.asOptional(), 432); // NOLINT(bugprone-unchecked-optional-access) EXPECT_EQ(vv2.asOptional(), std::nullopt); EXPECT_EQ(vv3.asOptional(), std::nullopt); EXPECT_EQ(vv4.asOptional(), "hello"); diff --git a/tests/unit/util/log/LogServiceInitTests.cpp b/tests/unit/util/log/LogServiceInitTests.cpp index ac3c0d55a..eab7a072f 100644 --- a/tests/unit/util/log/LogServiceInitTests.cpp +++ b/tests/unit/util/log/LogServiceInitTests.cpp @@ -211,6 +211,7 @@ TEST_F(LogServiceInitTests, LogSizeAndHourRotationCannotBeZero) auto const parsingErrors = config_.parse(ConfigFileJson{boost::json::parse(jsonStr).as_object()}); + // NOLINTBEGIN(bugprone-unchecked-optional-access) ASSERT_EQ(parsingErrors->size(), 2); for (std::size_t i = 0; i < parsingErrors->size(); ++i) { EXPECT_EQ( @@ -220,6 +221,7 @@ TEST_F(LogServiceInitTests, LogSizeAndHourRotationCannotBeZero) ) ); } + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(LogServiceInitTests, RotateDefaultsToTrue) diff --git a/tests/unit/util/prometheus/HistogramTests.cpp b/tests/unit/util/prometheus/HistogramTests.cpp index 7322cdf5d..0f70e5b29 100644 --- a/tests/unit/util/prometheus/HistogramTests.cpp +++ b/tests/unit/util/prometheus/HistogramTests.cpp @@ -61,7 +61,7 @@ struct HistogramTests : ::testing::Test { std::string labelsString = R"JSON({label1="value1",label2="value2"})JSON"; HistogramInt histogram{"t", labelsString, {1, 2, 3}}; - std::string + [[nodiscard]] std::string serialize() const { OStream stream{false}; diff --git a/tests/unit/util/prometheus/HttpTests.cpp b/tests/unit/util/prometheus/HttpTests.cpp index f2e104b2c..811c32714 100644 --- a/tests/unit/util/prometheus/HttpTests.cpp +++ b/tests/unit/util/prometheus/HttpTests.cpp @@ -100,9 +100,11 @@ TEST_F(PrometheusHandleRequestTests, emptyResponse) { auto response = handlePrometheusRequest(req, true); ASSERT_TRUE(response.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(response->result(), http::status::ok); EXPECT_EQ(response->operator[](http::field::content_type), "text/plain; version=0.0.4"); EXPECT_EQ(response->body(), ""); + // NOLINTEND(bugprone-unchecked-optional-access) } struct PrometheusDisabledHandleRequestTests : util::prometheus::WithPrometheusDisabled, @@ -112,6 +114,7 @@ TEST_F(PrometheusDisabledHandleRequestTests, prometheusDisabled) { auto response = handlePrometheusRequest(req, true); ASSERT_TRUE(response.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(response->result(), http::status::forbidden); } @@ -119,6 +122,7 @@ TEST_F(PrometheusHandleRequestTests, notAdmin) { auto response = handlePrometheusRequest(req, false); ASSERT_TRUE(response.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(response->result(), http::status::unauthorized); } @@ -134,6 +138,7 @@ TEST_F(PrometheusHandleRequestTests, responseWithCounter) auto response = handlePrometheusRequest(req, true); ASSERT_TRUE(response.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(response->result(), http::status::ok); EXPECT_EQ(response->operator[](http::field::content_type), "text/plain; version=0.0.4"); auto const expectedBody = fmt::format( @@ -143,6 +148,7 @@ TEST_F(PrometheusHandleRequestTests, responseWithCounter) labels.serialize() ); EXPECT_EQ(response->body(), expectedBody); + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(PrometheusHandleRequestTests, responseWithGauge) @@ -157,6 +163,7 @@ TEST_F(PrometheusHandleRequestTests, responseWithGauge) auto response = handlePrometheusRequest(req, true); ASSERT_TRUE(response.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(response->result(), http::status::ok); EXPECT_EQ(response->operator[](http::field::content_type), "text/plain; version=0.0.4"); auto const expectedBody = fmt::format( @@ -166,6 +173,7 @@ TEST_F(PrometheusHandleRequestTests, responseWithGauge) labels.serialize() ); EXPECT_EQ(response->body(), expectedBody); + // NOLINTEND(bugprone-unchecked-optional-access) } TEST_F(PrometheusHandleRequestTests, responseWithCounterAndGauge) @@ -188,7 +196,9 @@ TEST_F(PrometheusHandleRequestTests, responseWithCounterAndGauge) auto response = handlePrometheusRequest(req, true); - EXPECT_EQ(response->result(), http::status::ok); + ASSERT_TRUE(response.has_value()); + EXPECT_EQ(response->result(), http::status::ok); // NOLINT(bugprone-unchecked-optional-access) + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(response->operator[](http::field::content_type), "text/plain; version=0.0.4"); auto const expectedBody = fmt::format( "# HELP {3} {4}\n# TYPE {3} gauge\n{3}{5} -2\n\n" @@ -210,6 +220,7 @@ TEST_F(PrometheusHandleRequestTests, responseWithCounterAndGauge) gaugeDescription, gaugeLabels.serialize() ); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_TRUE(response->body() == expectedBody || response->body() == anotherExpectedBody); } @@ -227,8 +238,10 @@ TEST_F(PrometheusHandleRequestTests, compressReply) auto response = handlePrometheusRequest(req, true); ASSERT_TRUE(response.has_value()); + // NOLINTBEGIN(bugprone-unchecked-optional-access) EXPECT_EQ(response->result(), http::status::ok); EXPECT_EQ(response->operator[](http::field::content_type), "text/plain; version=0.0.4"); EXPECT_EQ(response->operator[](http::field::content_encoding), "gzip"); EXPECT_GT(response->body().size(), 0ul); + // NOLINTEND(bugprone-unchecked-optional-access) } diff --git a/tests/unit/web/ServerTests.cpp b/tests/unit/web/ServerTests.cpp index 6879e85a2..ad389502f 100644 --- a/tests/unit/web/ServerTests.cpp +++ b/tests/unit/web/ServerTests.cpp @@ -128,7 +128,7 @@ struct WebServerTest : public virtual ::testing::Test { { work_.reset(); ctx.stop(); - if (runner_->joinable()) + if (runner_.has_value() && runner_->joinable()) runner_->join(); } diff --git a/tests/unit/web/ng/RPCServerHandlerTests.cpp b/tests/unit/web/ng/RPCServerHandlerTests.cpp index f420159a4..ee06d0e59 100644 --- a/tests/unit/web/ng/RPCServerHandlerTests.cpp +++ b/tests/unit/web/ng/RPCServerHandlerTests.cpp @@ -247,7 +247,7 @@ TEST_F(NgRpcServerHandlerTest, DosguardAddsLoadWarning) EXPECT_EQ(responseJson.at("warning").as_string(), "load"); EXPECT_EQ( responseJson.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcRateLimit + static_cast(rpc::WarningCode::WarnRpcRateLimit) ); }); } @@ -351,7 +351,7 @@ TEST_F(NgRpcServerHandlerTest, HandleRequest_BuildResponseFailed) ASSERT_EQ(jsonResponse.at("warnings").as_array().size(), 1); EXPECT_EQ( jsonResponse.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcClio + static_cast(rpc::WarningCode::WarnRpcClio) ); }); } @@ -420,7 +420,7 @@ TEST_F(NgRpcServerHandlerTest, HandleRequest_Successful_HttpRequest) ASSERT_EQ(jsonResponse.at("warnings").as_array().size(), 1) << jsonResponse; EXPECT_EQ( jsonResponse.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcClio + static_cast(rpc::WarningCode::WarnRpcClio) ); }); } @@ -464,8 +464,8 @@ TEST_F(NgRpcServerHandlerTest, HandleRequest_OutdatedWarning) ); EXPECT_EQ(warningCodes.size(), 2); - EXPECT_TRUE(warningCodes.contains(rpc::WarnRpcClio)); - EXPECT_TRUE(warningCodes.contains(rpc::WarnRpcOutdated)); + EXPECT_TRUE(warningCodes.contains(static_cast(rpc::WarningCode::WarnRpcClio))); + EXPECT_TRUE(warningCodes.contains(static_cast(rpc::WarningCode::WarnRpcOutdated))); }); } @@ -508,7 +508,7 @@ TEST_F(NgRpcServerHandlerTest, HandleRequest_Successful_HttpRequest_Forwarded) ASSERT_EQ(jsonResponse.at("warnings").as_array().size(), 1) << jsonResponse; EXPECT_EQ( jsonResponse.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcClio + static_cast(rpc::WarningCode::WarnRpcClio) ); }); } @@ -551,7 +551,7 @@ TEST_F(NgRpcServerHandlerTest, HandleRequest_Successful_HttpRequest_HasError) ASSERT_EQ(jsonResponse.at("warnings").as_array().size(), 1) << jsonResponse; EXPECT_EQ( jsonResponse.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcClio + static_cast(rpc::WarningCode::WarnRpcClio) ); }); } @@ -617,7 +617,7 @@ TEST_F(NgRpcServerHandlerWsTest, HandleRequest_Successful_WsRequest) ASSERT_EQ(jsonResponse.at("warnings").as_array().size(), 1) << jsonResponse; EXPECT_EQ( jsonResponse.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcClio + static_cast(rpc::WarningCode::WarnRpcClio) ); }); } @@ -664,7 +664,7 @@ TEST_F(NgRpcServerHandlerWsTest, HandleRequest_Successful_WsRequest_HasError) ASSERT_EQ(jsonResponse.at("warnings").as_array().size(), 1) << jsonResponse; EXPECT_EQ( jsonResponse.at("warnings").as_array().at(0).as_object().at("id").as_int64(), - rpc::WarnRpcClio + static_cast(rpc::WarningCode::WarnRpcClio) ); }); } diff --git a/tests/unit/web/ng/RequestTests.cpp b/tests/unit/web/ng/RequestTests.cpp index 20adba06d..7bce2bd36 100644 --- a/tests/unit/web/ng/RequestTests.cpp +++ b/tests/unit/web/ng/RequestTests.cpp @@ -100,7 +100,8 @@ TEST_F(RequestAsHttpRequestTest, HttpRequest) Request const request{httpRequest}; auto const maybeHttpRequest = request.asHttpRequest(); ASSERT_TRUE(maybeHttpRequest.has_value()); - auto const& actualHttpRequest = maybeHttpRequest->get(); + auto const& actualHttpRequest = + maybeHttpRequest->get(); // NOLINT(bugprone-unchecked-optional-access) EXPECT_EQ(actualHttpRequest.method(), httpRequest.method()); EXPECT_EQ(actualHttpRequest.target(), httpRequest.target()); EXPECT_EQ(actualHttpRequest.version(), httpRequest.version()); @@ -204,7 +205,7 @@ TEST_F(RequestHeaderValueTest, headerValue) Request const request{httpRequest}; auto const maybeHeaderValue = request.headerValue(headerName); ASSERT_TRUE(maybeHeaderValue.has_value()); - EXPECT_EQ(maybeHeaderValue.value(), headerValue); + EXPECT_EQ(*maybeHeaderValue, headerValue); // NOLINT(bugprone-unchecked-optional-access) } TEST_F(RequestHeaderValueTest, headerValueString) @@ -216,7 +217,7 @@ TEST_F(RequestHeaderValueTest, headerValueString) Request const request{httpRequest}; auto const maybeHeaderValue = request.headerValue(headerName); ASSERT_TRUE(maybeHeaderValue.has_value()); - EXPECT_EQ(maybeHeaderValue.value(), headerValue); + EXPECT_EQ(*maybeHeaderValue, headerValue); // NOLINT(bugprone-unchecked-optional-access) } TEST_F(RequestHeaderValueTest, headerValueNotFound) @@ -236,5 +237,5 @@ TEST_F(RequestHeaderValueTest, headerValueWebsocketRequest) Request const request{"websocket message", headers}; auto const maybeHeaderValue = request.headerValue(headerName); ASSERT_TRUE(maybeHeaderValue.has_value()); - EXPECT_EQ(maybeHeaderValue.value(), headerValue); + EXPECT_EQ(*maybeHeaderValue, headerValue); // NOLINT(bugprone-unchecked-optional-access) } diff --git a/tests/unit/web/ng/ResponseTests.cpp b/tests/unit/web/ng/ResponseTests.cpp index b793b0ced..368a19720 100644 --- a/tests/unit/web/ng/ResponseTests.cpp +++ b/tests/unit/web/ng/ResponseTests.cpp @@ -41,7 +41,7 @@ TEST_F(ResponseAssertTest, asConstBufferWithHttpData) { Request const request{http::request{http::verb::get, "/", 11}}; Response const response{boost::beast::http::status::ok, "message", request}; - EXPECT_CLIO_ASSERT_FAIL(response.asWsResponse()); + EXPECT_CLIO_ASSERT_FAIL([&] { [[maybe_unused]] auto const _ = response.asWsResponse(); }()); } struct ResponseTest : testing::Test { @@ -64,6 +64,7 @@ TEST_F(ResponseTest, intoHttpResponse) EXPECT_EQ(httpResponse.result(), responseStatus_); EXPECT_EQ(httpResponse.body(), responseMessage); EXPECT_EQ(httpResponse.version(), httpVersion_); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(httpResponse.keep_alive(), request.asHttpRequest()->get().keep_alive()); ASSERT_GT(httpResponse.count(http::field::content_type), 0); @@ -89,6 +90,7 @@ TEST_F(ResponseTest, intoHttpResponseJson) EXPECT_EQ(httpResponse.result(), responseStatus_); EXPECT_EQ(httpResponse.body(), boost::json::serialize(responseMessage)); EXPECT_EQ(httpResponse.version(), httpVersion_); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_EQ(httpResponse.keep_alive(), request.asHttpRequest()->get().keep_alive()); ASSERT_GT(httpResponse.count(http::field::content_type), 0); diff --git a/tests/unit/web/ng/ServerTests.cpp b/tests/unit/web/ng/ServerTests.cpp index 3b2633f0a..36cd6a260 100644 --- a/tests/unit/web/ng/ServerTests.cpp +++ b/tests/unit/web/ng/ServerTests.cpp @@ -229,6 +229,7 @@ TEST_F(ServerTest, BadEndpoint) auto maybeError = server.run(); ASSERT_TRUE(maybeError.has_value()); + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) EXPECT_THAT(*maybeError, testing::HasSubstr("Error creating TCP acceptor")); } @@ -236,7 +237,7 @@ struct ServerHttpTestBundle { std::string testName; http::verb method; - Request::Method + [[nodiscard]] Request::Method expectedMethod() const { switch (method) { diff --git a/tests/unit/web/ng/impl/ErrorHandlingTests.cpp b/tests/unit/web/ng/impl/ErrorHandlingTests.cpp index b0941ed02..b01ff2d98 100644 --- a/tests/unit/web/ng/impl/ErrorHandlingTests.cpp +++ b/tests/unit/web/ng/impl/ErrorHandlingTests.cpp @@ -140,6 +140,7 @@ TEST_P(NgErrorHandlingMakeInternalErrorTest, ComposeError) { auto const request = makeRequest(GetParam().isHttp, GetParam().request); std::optional const requestJson = GetParam().request.has_value() + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) ? std::make_optional(boost::json::parse(*GetParam().request).as_object()) : std::nullopt; ErrorHelper const errorHelper{request, requestJson}; diff --git a/tests/unit/web/ng/impl/ServerSslContextTests.cpp b/tests/unit/web/ng/impl/ServerSslContextTests.cpp index bb17a1f62..fb324c563 100644 --- a/tests/unit/web/ng/impl/ServerSslContextTests.cpp +++ b/tests/unit/web/ng/impl/ServerSslContextTests.cpp @@ -24,7 +24,7 @@ struct MakeServerSslContextFromConfigTestBundle { std::optional expectedError; bool expectContext; - boost::json::value + [[nodiscard]] boost::json::value configJson() const { boost::json::object result; @@ -57,7 +57,9 @@ TEST_P(MakeServerSslContextFromConfigTest, makeFromConfig) if (GetParam().expectedError.has_value()) { ASSERT_FALSE(expectedServerSslContext.has_value()); EXPECT_THAT( - expectedServerSslContext.error(), testing::HasSubstr(*GetParam().expectedError) + expectedServerSslContext.error(), + // NOLINTNEXTLINE(bugprone-unchecked-optional-access) + testing::HasSubstr(*GetParam().expectedError) ); } else { EXPECT_EQ(expectedServerSslContext.value().has_value(), GetParam().expectContext);