Implement FileCollector with concurrency and stress tests
This commit is contained in:
parent
d09fb340b7
commit
4c05fe8034
26 changed files with 1745 additions and 0 deletions
0
.Rhistory
Normal file
0
.Rhistory
Normal file
11
.gitignore
vendored
Normal file
11
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
/build*/
|
||||||
|
/.cache/
|
||||||
|
/.DS_Store
|
||||||
|
*.profraw
|
||||||
|
*.profdata
|
||||||
|
*.gcda
|
||||||
|
*.gcno
|
||||||
|
*.gcov
|
||||||
|
*.dSYM/
|
||||||
|
*.zip
|
||||||
|
|
||||||
48
CMakeLists.txt
Normal file
48
CMakeLists.txt
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
cmake_minimum_required(VERSION 3.25)
|
||||||
|
project(FileByChunks VERSION 1.0.0 LANGUAGES CXX)
|
||||||
|
|
||||||
|
set(CMAKE_CXX_STANDARD 20)
|
||||||
|
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||||
|
set(CMAKE_CXX_EXTENSIONS OFF)
|
||||||
|
|
||||||
|
option(FILE_COLLECTOR_BUILD_TESTS "Build GoogleTest suite" ON)
|
||||||
|
option(FILE_COLLECTOR_ASAN_UBSAN "Enable AddressSanitizer and UndefinedBehaviorSanitizer" OFF)
|
||||||
|
option(FILE_COLLECTOR_TSAN "Enable ThreadSanitizer" OFF)
|
||||||
|
|
||||||
|
if(FILE_COLLECTOR_ASAN_UBSAN AND FILE_COLLECTOR_TSAN)
|
||||||
|
message(FATAL_ERROR "Use ASan/UBSan and TSan in separate builds")
|
||||||
|
endif()
|
||||||
|
|
||||||
|
if(FILE_COLLECTOR_ASAN_UBSAN OR FILE_COLLECTOR_TSAN)
|
||||||
|
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang|GNU")
|
||||||
|
message(FATAL_ERROR "The selected sanitizers require Clang or GCC")
|
||||||
|
endif()
|
||||||
|
if(FILE_COLLECTOR_TSAN)
|
||||||
|
set(SANITIZER_FLAGS -fsanitize=thread -fno-omit-frame-pointer -g)
|
||||||
|
else()
|
||||||
|
set(SANITIZER_FLAGS -fsanitize=address,undefined -fno-omit-frame-pointer -g)
|
||||||
|
endif()
|
||||||
|
add_compile_options(${SANITIZER_FLAGS})
|
||||||
|
add_link_options(${SANITIZER_FLAGS})
|
||||||
|
endif()
|
||||||
|
|
||||||
|
find_package(Threads REQUIRED)
|
||||||
|
|
||||||
|
add_library(file_collector SHARED
|
||||||
|
src/file_collector.cpp
|
||||||
|
src/file_state.cpp
|
||||||
|
src/thread_pool.cpp
|
||||||
|
)
|
||||||
|
target_include_directories(file_collector PUBLIC include PRIVATE src)
|
||||||
|
target_link_libraries(file_collector PRIVATE Threads::Threads)
|
||||||
|
target_compile_features(file_collector PUBLIC cxx_std_20)
|
||||||
|
set_target_properties(file_collector PROPERTIES
|
||||||
|
CXX_VISIBILITY_PRESET default
|
||||||
|
VISIBILITY_INLINES_HIDDEN OFF
|
||||||
|
)
|
||||||
|
|
||||||
|
if(FILE_COLLECTOR_BUILD_TESTS)
|
||||||
|
include(CTest)
|
||||||
|
add_subdirectory(tests)
|
||||||
|
endif()
|
||||||
|
|
||||||
107
README.md
Normal file
107
README.md
Normal file
|
|
@ -0,0 +1,107 @@
|
||||||
|
# FileByChunks — FileCollector
|
||||||
|
|
||||||
|
**Дата спецификации:** 06.11.2026. **Язык:** C++20. **Сборка:** CMake ≥ 3.25.
|
||||||
|
**Тесты:** GoogleTest и CTest. **Целевая ОС:** macOS, также Linux.
|
||||||
|
|
||||||
|
Потокобезопасное восстановление файлов из пересекающихся, дублирующихся и
|
||||||
|
поступающих в произвольном порядке чанков. Библиотека работает только с RAM.
|
||||||
|
Публичный полиморфный контракт расположен в
|
||||||
|
`include/file_collector/i_file_collector.hpp`.
|
||||||
|
|
||||||
|
## Контракт
|
||||||
|
|
||||||
|
- `CollectFile(id, size)` регистрирует файл; повторный `id` запрещён.
|
||||||
|
- `OnNewChunk(id, pos, vector<uint8_t>&&)` асинхронно ставит чанк в ThreadPool.
|
||||||
|
Проверка `id` и границ синхронная. Чанки после завершения файла игнорируются.
|
||||||
|
- `GetFile(id, check_complete)` ждёт только задачи этого файла и возвращает
|
||||||
|
`shared_ptr<const vector<uint8_t>>`. Готовый файл возвращается без копии.
|
||||||
|
- `GetFile(id, pos, length, check_complete)` ждёт задачи и возвращает
|
||||||
|
отдельный неизменяемый снимок диапазона.
|
||||||
|
- `TakeFile(id, check_complete)` ждёт задачи, возвращает изменяемый
|
||||||
|
`shared_ptr<vector<uint8_t>>` и снимает регистрацию. Если общий готовый
|
||||||
|
буфер уже находится у читателя, выполняется копирование ради неизменяемости
|
||||||
|
ранее выданного `FileView`.
|
||||||
|
- `RemoveFile(id)` удаляет регистрацию; `ClearFile(id)` обнуляет данные,
|
||||||
|
сохраняет регистрацию и начинает сборку заново.
|
||||||
|
|
||||||
|
Полнота проверяется по умолчанию. `check_complete=false` разрешает неполный
|
||||||
|
снимок с нулями в ещё не записанных позициях. Ошибки полноты —
|
||||||
|
`std::logic_error`, неверные `id` или границы — `std::out_of_range`,
|
||||||
|
асинхронные ошибки сохраняются до `ClearFile` и передаются через `GetFile`
|
||||||
|
или `TakeFile`. Параллельные операции жизненного цикла одного файла
|
||||||
|
сериализованы; обращения во время закрытия могут получить `logic_error`.
|
||||||
|
|
||||||
|
## Сборка на macOS
|
||||||
|
|
||||||
|
Из корня проекта:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release
|
||||||
|
cmake --build build-release --parallel
|
||||||
|
ctest --test-dir build-release --output-on-failure
|
||||||
|
```
|
||||||
|
|
||||||
|
GoogleTest находится через `find_package(GTest CONFIG)` или загружается
|
||||||
|
`FetchContent` по фиксированному commit. Для работы без сети можно указать
|
||||||
|
`-DFILE_COLLECTOR_GTEST_SOURCE_DIR=/path/to/googletest` при конфигурации.
|
||||||
|
|
||||||
|
### Санитайзеры (две отдельные сборки)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cmake -S . -B build-asan -DCMAKE_BUILD_TYPE=Debug -DFILE_COLLECTOR_ASAN_UBSAN=ON
|
||||||
|
cmake --build build-asan --parallel
|
||||||
|
ctest --test-dir build-asan --output-on-failure
|
||||||
|
|
||||||
|
cmake -S . -B build-tsan -DCMAKE_BUILD_TYPE=Debug -DFILE_COLLECTOR_TSAN=ON
|
||||||
|
cmake --build build-tsan --parallel
|
||||||
|
ctest --test-dir build-tsan --output-on-failure
|
||||||
|
```
|
||||||
|
|
||||||
|
На Apple Silicon/AppleClang совместимость и доступность санитайзеров зависят
|
||||||
|
от поставки компилятора; если TSan не поддерживается, используйте отдельную
|
||||||
|
поддерживаемую сборочную среду. ASan/UBSan и TSan не совмещаются.
|
||||||
|
В окружениях с `ptrace` LeakSanitizer может завершаться аварийно; в таком
|
||||||
|
случае отдельный диагностический прогон возможен с
|
||||||
|
`ASAN_OPTIONS=detect_leaks=0`, но он **не проверяет утечки памяти**.
|
||||||
|
|
||||||
|
### Профилирование
|
||||||
|
|
||||||
|
Тест `Performance.BaselineMiBPerSecondAndSubmissionLatency` выводит
|
||||||
|
throughput, p50/p95 **времени вызова постановки чанка** и пиковую RSS
|
||||||
|
процесса. Это не p50/p95 выполнения задач ThreadPool, не время удержания
|
||||||
|
mutex и не точный пик собственной памяти FileCollector.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
./build-release/tests/file_collector_tests --gtest_filter=Performance.*
|
||||||
|
```
|
||||||
|
|
||||||
|
Для системного профилирования на macOS можно дополнительно применить
|
||||||
|
встроенный Xcode Instruments, например шаблон Time Profiler. Выводы о
|
||||||
|
производительности нужно делать по повторным прогонам на целевой машине.
|
||||||
|
|
||||||
|
## Организация
|
||||||
|
|
||||||
|
- `include/` — внешний интерфейс и класс.
|
||||||
|
- `src/` — реестр, состояние, две побайтовые битовые маски, ThreadPool.
|
||||||
|
- `tests/` — корректность, границы, снимки, жизненный цикл, многопоточность,
|
||||||
|
инъекция отказов, нагрузка и метрики.
|
||||||
|
- `Stress.RandomizedOverlapSpectrumAcrossSizesAndSeeds` проверяет 8 размеров
|
||||||
|
файлов × 4 фиксированных seed, случайную длину/позицию чанков, полные
|
||||||
|
дубликаты и пересечения от 1 байта до 100%; одновременно работают
|
||||||
|
8 producers. Случайная исходная разбивка гарантирует покрытие всего файла.
|
||||||
|
- `Stress.RandomizedSnapshotsStayImmutableDuringConcurrentIngestion`
|
||||||
|
проверяет 32 снимка при параллельном приёме четырьмя producers и
|
||||||
|
неизменяемость исходного пустого снимка после окончательной сборки.
|
||||||
|
- `src/fault_injector.hpp` — внутренние, необязательные точки отказа,
|
||||||
|
передаваемые конструктору для детерминированных тестов.
|
||||||
|
|
||||||
|
В нормальном конструкторе число workers равно
|
||||||
|
`std::thread::hardware_concurrency()` (fallback — 1 при нуле).
|
||||||
|
При тестировании разрешена явная настройка числа работников через конструктор.
|
||||||
|
|
||||||
|
## Сдача
|
||||||
|
|
||||||
|
ZIP: `Владислав_Агибалов_С++.zip` — исходники, CMake, тесты, README.
|
||||||
|
В Skillaz отдельно подаётся `Выполнено.txt`, содержащий слово `Выполнено`.
|
||||||
|
Бинарные артефакты, сборочные директории и `.git` в ZIP не включать.
|
||||||
|
|
||||||
38
include/file_collector/file_collector.hpp
Normal file
38
include/file_collector/file_collector.hpp
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "file_collector/i_file_collector.hpp"
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
|
||||||
|
namespace file_collector {
|
||||||
|
namespace detail { class FaultInjector; }
|
||||||
|
class FileCollectorImpl;
|
||||||
|
|
||||||
|
class FileCollector final : public IFileCollector {
|
||||||
|
public:
|
||||||
|
explicit FileCollector(
|
||||||
|
std::size_t workers = 0,
|
||||||
|
std::shared_ptr<detail::FaultInjector> fault_injector = {});
|
||||||
|
~FileCollector() override;
|
||||||
|
FileCollector(const FileCollector&) = delete;
|
||||||
|
FileCollector& operator=(const FileCollector&) = delete;
|
||||||
|
FileCollector(FileCollector&&) = delete;
|
||||||
|
FileCollector& operator=(FileCollector&&) = delete;
|
||||||
|
|
||||||
|
void CollectFile(std::uint32_t file_id, std::size_t file_size) override;
|
||||||
|
void OnNewChunk(std::uint32_t file_id, std::size_t pos, FileBytes&& chunk) override;
|
||||||
|
[[nodiscard]] FileView GetFile(std::uint32_t file_id, bool check_complete = true) override;
|
||||||
|
[[nodiscard]] FileView GetFile(std::uint32_t file_id, std::size_t pos,
|
||||||
|
std::size_t length, bool check_complete = true) override;
|
||||||
|
[[nodiscard]] MutableFile TakeFile(std::uint32_t file_id, bool check_complete = true) override;
|
||||||
|
void RemoveFile(std::uint32_t file_id) override;
|
||||||
|
void ClearFile(std::uint32_t file_id) override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::unique_ptr<FileCollectorImpl> impl_;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace file_collector
|
||||||
|
|
||||||
30
include/file_collector/i_file_collector.hpp
Normal file
30
include/file_collector/i_file_collector.hpp
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace file_collector {
|
||||||
|
|
||||||
|
using FileBytes = std::vector<std::uint8_t>;
|
||||||
|
using FileView = std::shared_ptr<const FileBytes>;
|
||||||
|
using MutableFile = std::shared_ptr<FileBytes>;
|
||||||
|
|
||||||
|
class IFileCollector {
|
||||||
|
public:
|
||||||
|
virtual ~IFileCollector() = default;
|
||||||
|
|
||||||
|
virtual void CollectFile(std::uint32_t file_id, std::size_t file_size) = 0;
|
||||||
|
virtual void OnNewChunk(std::uint32_t file_id, std::size_t pos, FileBytes&& chunk) = 0;
|
||||||
|
[[nodiscard]] virtual FileView GetFile(std::uint32_t file_id, bool check_complete = true) = 0;
|
||||||
|
[[nodiscard]] virtual FileView GetFile(
|
||||||
|
std::uint32_t file_id, std::size_t pos, std::size_t length,
|
||||||
|
bool check_complete = true) = 0;
|
||||||
|
[[nodiscard]] virtual MutableFile TakeFile(std::uint32_t file_id, bool check_complete = true) = 0;
|
||||||
|
virtual void RemoveFile(std::uint32_t file_id) = 0;
|
||||||
|
virtual void ClearFile(std::uint32_t file_id) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace file_collector
|
||||||
|
|
||||||
94
scripts/generate_vim_guide.py
Normal file
94
scripts/generate_vim_guide.py
Normal file
|
|
@ -0,0 +1,94 @@
|
||||||
|
"""Build the exact copy/paste Vim guide from the verified project sources."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
PROJECT = Path(__file__).resolve().parent.parent
|
||||||
|
DESTINATION = PROJECT.parent / "FileByChunks_VIM_GUIDE.md"
|
||||||
|
ORDER = [
|
||||||
|
"CMakeLists.txt",
|
||||||
|
"tests/CMakeLists.txt",
|
||||||
|
"tests/test_data.hpp",
|
||||||
|
"tests/collector_tests.cpp",
|
||||||
|
"tests/chunk_tests.cpp",
|
||||||
|
"tests/boundary_tests.cpp",
|
||||||
|
"tests/concurrency_tests.cpp",
|
||||||
|
"tests/lifecycle_tests.cpp",
|
||||||
|
"tests/snapshot_tests.cpp",
|
||||||
|
"tests/exception_tests.cpp",
|
||||||
|
"tests/thread_pool_tests.cpp",
|
||||||
|
"tests/stress_tests.cpp",
|
||||||
|
"tests/performance_tests.cpp",
|
||||||
|
"include/file_collector/i_file_collector.hpp",
|
||||||
|
"include/file_collector/file_collector.hpp",
|
||||||
|
"src/fault_injector.hpp",
|
||||||
|
"src/thread_pool.hpp",
|
||||||
|
"src/file_state.hpp",
|
||||||
|
"src/thread_pool.cpp",
|
||||||
|
"src/file_state.cpp",
|
||||||
|
"src/file_collector.cpp",
|
||||||
|
".gitignore",
|
||||||
|
"scripts/package.sh",
|
||||||
|
"scripts/generate_vim_guide.py",
|
||||||
|
"README.md",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def output() -> str:
|
||||||
|
lines = [
|
||||||
|
"# FileByChunks — полные блоки файлов для Vim",
|
||||||
|
"",
|
||||||
|
"Актуальность: 06.11.2026. Порядок: иерархия → CMake → тесты → исходники.",
|
||||||
|
"У каждого файла сначала команда `vim`, затем полный текст для вставки.",
|
||||||
|
"",
|
||||||
|
"```bash",
|
||||||
|
"mkdir -p /Users/avs/safeboard/2026/11/cpp/FileByChunks",
|
||||||
|
"cd /Users/avs/safeboard/2026/11/cpp/FileByChunks",
|
||||||
|
"git init -b main",
|
||||||
|
"git remote add origin git@github.com:multmine1/safeboard_2026_11_Cpp_chunks_-.git",
|
||||||
|
"mkdir -p include/file_collector src tests scripts",
|
||||||
|
"```",
|
||||||
|
"",
|
||||||
|
]
|
||||||
|
for filename in ORDER:
|
||||||
|
data = (PROJECT / filename).read_text(encoding="utf-8")
|
||||||
|
language = "cmake" if filename.endswith("CMakeLists.txt") else "bash" if filename.endswith(".sh") else "cpp" if filename.endswith((".cpp", ".hpp")) else "python" if filename.endswith(".py") else "text"
|
||||||
|
lines.extend([
|
||||||
|
f"## `{filename}`",
|
||||||
|
"",
|
||||||
|
"```bash",
|
||||||
|
f"vim {filename}",
|
||||||
|
"```",
|
||||||
|
"",
|
||||||
|
f"```{language}",
|
||||||
|
data.rstrip("\n"),
|
||||||
|
"```",
|
||||||
|
"",
|
||||||
|
])
|
||||||
|
lines.extend([
|
||||||
|
"## Сборка, тесты и сдача",
|
||||||
|
"",
|
||||||
|
"```bash",
|
||||||
|
"cmake -S . -B build-release -DCMAKE_BUILD_TYPE=Release",
|
||||||
|
"cmake --build build-release --parallel",
|
||||||
|
"ctest --test-dir build-release --output-on-failure",
|
||||||
|
"cmake -S . -B build-asan -DCMAKE_BUILD_TYPE=Debug -DFILE_COLLECTOR_ASAN_UBSAN=ON",
|
||||||
|
"cmake --build build-asan --parallel",
|
||||||
|
"ctest --test-dir build-asan --output-on-failure",
|
||||||
|
"cmake -S . -B build-tsan -DCMAKE_BUILD_TYPE=Debug -DFILE_COLLECTOR_TSAN=ON",
|
||||||
|
"cmake --build build-tsan --parallel",
|
||||||
|
"ctest --test-dir build-tsan --output-on-failure",
|
||||||
|
"bash scripts/package.sh",
|
||||||
|
"printf 'Выполнено\\n' > ../Выполнено.txt",
|
||||||
|
"```",
|
||||||
|
"",
|
||||||
|
"ZIP отправляется в Kaspersky Box, TXT — в Skillaz.",
|
||||||
|
"",
|
||||||
|
])
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
DESTINATION.write_text(output(), encoding="utf-8")
|
||||||
|
print(DESTINATION)
|
||||||
|
|
||||||
19
scripts/package.sh
Normal file
19
scripts/package.sh
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
project_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
project_name="$(basename "$project_dir")"
|
||||||
|
parent_dir="$(dirname "$project_dir")"
|
||||||
|
archive_name="Владислав_Агибалов_С++.zip"
|
||||||
|
|
||||||
|
cd "$parent_dir"
|
||||||
|
zip -r -FS "$archive_name" "$project_name" \
|
||||||
|
-x "$project_name/.git/*" \
|
||||||
|
"$project_name/build*/*" \
|
||||||
|
"$project_name/.cache/*" \
|
||||||
|
"$project_name/.DS_Store" \
|
||||||
|
"$project_name/*.dSYM/*" \
|
||||||
|
"$project_name/*.zip"
|
||||||
|
|
||||||
|
printf 'Архив: %s\n' "$parent_dir/$archive_name"
|
||||||
|
|
||||||
19
src/fault_injector.hpp
Normal file
19
src/fault_injector.hpp
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
namespace file_collector::detail {
|
||||||
|
|
||||||
|
enum class FaultPoint {
|
||||||
|
BeforeEnqueue,
|
||||||
|
AfterReserve,
|
||||||
|
BeforeCopy,
|
||||||
|
BeforeCommit,
|
||||||
|
};
|
||||||
|
|
||||||
|
class FaultInjector {
|
||||||
|
public:
|
||||||
|
virtual ~FaultInjector() = default;
|
||||||
|
virtual void Hit(FaultPoint point) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace file_collector::detail
|
||||||
|
|
||||||
273
src/file_collector.cpp
Normal file
273
src/file_collector.cpp
Normal file
|
|
@ -0,0 +1,273 @@
|
||||||
|
#include "file_collector/file_collector.hpp"
|
||||||
|
|
||||||
|
#include "fault_injector.hpp"
|
||||||
|
#include "file_state.hpp"
|
||||||
|
#include "thread_pool.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <bit>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <exception>
|
||||||
|
#include <mutex>
|
||||||
|
#include <ranges>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <thread>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace file_collector {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
using detail::FileState;
|
||||||
|
using detail::WordReservation;
|
||||||
|
|
||||||
|
void Hit(const std::shared_ptr<detail::FaultInjector>& injector, detail::FaultPoint point) {
|
||||||
|
if (injector) {
|
||||||
|
injector->Hit(point);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CopyReserved(const FileState& state, std::size_t pos, const FileBytes& chunk,
|
||||||
|
const std::vector<WordReservation>& reservations) {
|
||||||
|
for (const auto& reservation : reservations) {
|
||||||
|
auto remaining = reservation.bits;
|
||||||
|
while (remaining != 0) {
|
||||||
|
const auto first_bit = std::countr_zero(remaining);
|
||||||
|
const auto count = std::countr_one(remaining >> first_bit);
|
||||||
|
const auto dst_pos = reservation.word_index * 64 + first_bit;
|
||||||
|
std::ranges::copy_n(chunk.data() + (dst_pos - pos), count,
|
||||||
|
state.data_->data() + dst_pos);
|
||||||
|
const auto run = count == 64
|
||||||
|
? ~std::uint64_t{0}
|
||||||
|
: ((std::uint64_t{1} << count) - 1) << first_bit;
|
||||||
|
remaining &= ~run;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ProcessChunk(std::shared_ptr<FileState> state, std::size_t pos, FileBytes chunk,
|
||||||
|
std::shared_ptr<detail::FaultInjector> injector) noexcept {
|
||||||
|
std::vector<WordReservation> reservations;
|
||||||
|
try {
|
||||||
|
{
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
reservations = state->Reserve(pos, chunk.size());
|
||||||
|
}
|
||||||
|
if (!reservations.empty()) {
|
||||||
|
Hit(injector, detail::FaultPoint::AfterReserve);
|
||||||
|
Hit(injector, detail::FaultPoint::BeforeCopy);
|
||||||
|
CopyReserved(*state, pos, chunk, reservations);
|
||||||
|
Hit(injector, detail::FaultPoint::BeforeCommit);
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
state->Commit(reservations);
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
state->Rollback(reservations);
|
||||||
|
if (!state->error_) {
|
||||||
|
state->error_ = std::current_exception();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
detail::CompleteTask(*state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void CheckUsable(const FileState& state) {
|
||||||
|
if (state.removed_ || state.closing_) {
|
||||||
|
throw std::logic_error("file is being removed, taken, or cleared");
|
||||||
|
}
|
||||||
|
if (state.error_) {
|
||||||
|
std::rethrow_exception(state.error_);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <class Action>
|
||||||
|
auto WithIdleFile(const std::shared_ptr<FileState>& state, Action action) {
|
||||||
|
for (;;) {
|
||||||
|
detail::WaitIdle(*state);
|
||||||
|
std::unique_lock lock(state->mutex_);
|
||||||
|
if (state->pending_tasks_.load(std::memory_order_acquire) != 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
CheckUsable(*state);
|
||||||
|
return action(*state);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
class FileCollectorImpl final {
|
||||||
|
public:
|
||||||
|
explicit FileCollectorImpl(std::size_t workers, std::shared_ptr<detail::FaultInjector> injector)
|
||||||
|
: injector_(std::move(injector)),
|
||||||
|
pool_(workers == 0 ? std::thread::hardware_concurrency() : workers) {}
|
||||||
|
|
||||||
|
void CollectFile(std::uint32_t file_id, std::size_t file_size) {
|
||||||
|
auto state = std::make_shared<FileState>(file_size);
|
||||||
|
std::lock_guard lock(registry_mutex_);
|
||||||
|
if (!files_.emplace(file_id, std::move(state)).second) {
|
||||||
|
throw std::logic_error("file identifier is already registered");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void OnNewChunk(std::uint32_t file_id, std::size_t pos, FileBytes&& chunk) {
|
||||||
|
auto state = Find(file_id);
|
||||||
|
detail::ValidateRange(state->file_size_, pos, chunk.size());
|
||||||
|
{
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
CheckUsable(*state);
|
||||||
|
if (state->ready_ || chunk.empty()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
state->pending_tasks_.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
Hit(injector_, detail::FaultPoint::BeforeEnqueue);
|
||||||
|
pool_.Submit([state, pos, chunk = std::move(chunk), injector = injector_]() mutable {
|
||||||
|
ProcessChunk(std::move(state), pos, std::move(chunk), std::move(injector));
|
||||||
|
});
|
||||||
|
} catch (...) {
|
||||||
|
detail::CompleteTask(*state);
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] FileView GetFile(std::uint32_t file_id, bool check_complete) {
|
||||||
|
return WithIdleFile(Find(file_id), [check_complete](const FileState& state) -> FileView {
|
||||||
|
if (check_complete && !state.ready_) {
|
||||||
|
throw std::logic_error("file is incomplete");
|
||||||
|
}
|
||||||
|
if (state.ready_) {
|
||||||
|
return state.data_; // No byte copy for finalized files.
|
||||||
|
}
|
||||||
|
return std::make_shared<const FileBytes>(*state.data_);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] FileView GetFile(std::uint32_t file_id, std::size_t pos,
|
||||||
|
std::size_t length, bool check_complete) {
|
||||||
|
auto state = Find(file_id);
|
||||||
|
detail::ValidateRange(state->file_size_, pos, length);
|
||||||
|
return WithIdleFile(state, [=](const FileState& locked) -> FileView {
|
||||||
|
if (check_complete && !locked.RangeWritten(pos, length)) {
|
||||||
|
throw std::logic_error("requested range is incomplete");
|
||||||
|
}
|
||||||
|
const auto first = locked.data_->begin() + static_cast<std::ptrdiff_t>(pos);
|
||||||
|
return std::make_shared<const FileBytes>(first, first + static_cast<std::ptrdiff_t>(length));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
[[nodiscard]] MutableFile TakeFile(std::uint32_t file_id, bool check_complete) {
|
||||||
|
auto state = Find(file_id);
|
||||||
|
std::unique_lock lifecycle(state->lifecycle_mutex_);
|
||||||
|
BeginClosing(*state);
|
||||||
|
detail::WaitIdle(*state);
|
||||||
|
MutableFile result;
|
||||||
|
{
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
try {
|
||||||
|
if (state->error_) {
|
||||||
|
std::rethrow_exception(state->error_);
|
||||||
|
}
|
||||||
|
if (check_complete && !state->ready_) {
|
||||||
|
throw std::logic_error("file is incomplete");
|
||||||
|
}
|
||||||
|
result = state->data_.use_count() == 1
|
||||||
|
? std::move(state->data_)
|
||||||
|
: std::make_shared<FileBytes>(*state->data_);
|
||||||
|
state->removed_ = true;
|
||||||
|
} catch (...) {
|
||||||
|
state->closing_ = false;
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EraseSame(file_id, state);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RemoveFile(std::uint32_t file_id) {
|
||||||
|
auto state = Find(file_id);
|
||||||
|
std::unique_lock lifecycle(state->lifecycle_mutex_);
|
||||||
|
BeginClosing(*state);
|
||||||
|
detail::WaitIdle(*state);
|
||||||
|
{
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
state->removed_ = true;
|
||||||
|
}
|
||||||
|
EraseSame(file_id, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ClearFile(std::uint32_t file_id) {
|
||||||
|
auto state = Find(file_id);
|
||||||
|
std::unique_lock lifecycle(state->lifecycle_mutex_);
|
||||||
|
BeginClosing(*state);
|
||||||
|
detail::WaitIdle(*state);
|
||||||
|
try {
|
||||||
|
auto fresh = std::make_shared<FileBytes>(state->file_size_, 0);
|
||||||
|
const auto words = state->file_size_ / 64 + (state->file_size_ % 64 != 0);
|
||||||
|
std::vector<std::uint64_t> written(words, 0);
|
||||||
|
std::vector<std::uint64_t> in_progress(words, 0);
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
state->Reset(std::move(fresh), std::move(written), std::move(in_progress));
|
||||||
|
} catch (...) {
|
||||||
|
std::lock_guard lock(state->mutex_);
|
||||||
|
state->closing_ = false;
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
[[nodiscard]] std::shared_ptr<FileState> Find(std::uint32_t file_id) const {
|
||||||
|
std::lock_guard lock(registry_mutex_);
|
||||||
|
const auto it = files_.find(file_id);
|
||||||
|
if (it == files_.end()) {
|
||||||
|
throw std::out_of_range("unknown file identifier");
|
||||||
|
}
|
||||||
|
return it->second;
|
||||||
|
}
|
||||||
|
|
||||||
|
void EraseSame(std::uint32_t file_id, const std::shared_ptr<FileState>& state) {
|
||||||
|
std::lock_guard lock(registry_mutex_);
|
||||||
|
const auto it = files_.find(file_id);
|
||||||
|
if (it != files_.end() && it->second == state) {
|
||||||
|
files_.erase(it);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void BeginClosing(FileState& state) {
|
||||||
|
std::lock_guard lock(state.mutex_);
|
||||||
|
if (state.removed_ || state.closing_) {
|
||||||
|
throw std::logic_error("file is no longer registered or is closing");
|
||||||
|
}
|
||||||
|
state.closing_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
mutable std::mutex registry_mutex_;
|
||||||
|
std::unordered_map<std::uint32_t, std::shared_ptr<FileState>> files_;
|
||||||
|
std::shared_ptr<detail::FaultInjector> injector_;
|
||||||
|
detail::ThreadPool pool_; // Destroyed first; tasks drain before registry destruction.
|
||||||
|
};
|
||||||
|
|
||||||
|
FileCollector::FileCollector(std::size_t workers, std::shared_ptr<detail::FaultInjector> fault_injector)
|
||||||
|
: impl_(std::make_unique<FileCollectorImpl>(workers, std::move(fault_injector))) {}
|
||||||
|
FileCollector::~FileCollector() = default;
|
||||||
|
void FileCollector::CollectFile(std::uint32_t file_id, std::size_t file_size) {
|
||||||
|
impl_->CollectFile(file_id, file_size);
|
||||||
|
}
|
||||||
|
void FileCollector::OnNewChunk(std::uint32_t file_id, std::size_t pos, FileBytes&& chunk) {
|
||||||
|
impl_->OnNewChunk(file_id, pos, std::move(chunk));
|
||||||
|
}
|
||||||
|
FileView FileCollector::GetFile(std::uint32_t file_id, bool check_complete) {
|
||||||
|
return impl_->GetFile(file_id, check_complete);
|
||||||
|
}
|
||||||
|
FileView FileCollector::GetFile(std::uint32_t file_id, std::size_t pos,
|
||||||
|
std::size_t length, bool check_complete) {
|
||||||
|
return impl_->GetFile(file_id, pos, length, check_complete);
|
||||||
|
}
|
||||||
|
MutableFile FileCollector::TakeFile(std::uint32_t file_id, bool check_complete) {
|
||||||
|
return impl_->TakeFile(file_id, check_complete);
|
||||||
|
}
|
||||||
|
void FileCollector::RemoveFile(std::uint32_t file_id) { impl_->RemoveFile(file_id); }
|
||||||
|
void FileCollector::ClearFile(std::uint32_t file_id) { impl_->ClearFile(file_id); }
|
||||||
|
|
||||||
|
} // namespace file_collector
|
||||||
|
|
||||||
121
src/file_state.cpp
Normal file
121
src/file_state.cpp
Normal file
|
|
@ -0,0 +1,121 @@
|
||||||
|
#include "file_state.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <bit>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace file_collector::detail {
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr std::size_t kWordBits = 64;
|
||||||
|
|
||||||
|
std::uint64_t RangeMask(std::size_t word_index, std::size_t pos, std::size_t end) noexcept {
|
||||||
|
const auto start = word_index * kWordBits;
|
||||||
|
const auto low = pos > start ? pos - start : 0;
|
||||||
|
const auto high = std::min(kWordBits, end - start);
|
||||||
|
const auto low_mask = ~std::uint64_t{0} << low;
|
||||||
|
const auto high_mask = high == kWordBits
|
||||||
|
? ~std::uint64_t{0}
|
||||||
|
: (std::uint64_t{1} << high) - 1;
|
||||||
|
return low_mask & high_mask;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t WordCount(std::size_t file_size) noexcept {
|
||||||
|
return file_size / kWordBits + (file_size % kWordBits != 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
FileState::FileState(std::size_t file_size)
|
||||||
|
: data_(std::make_shared<FileBytes>(file_size, 0)),
|
||||||
|
written_(WordCount(file_size), 0),
|
||||||
|
in_progress_(WordCount(file_size), 0),
|
||||||
|
file_size_(file_size),
|
||||||
|
ready_(file_size == 0) {}
|
||||||
|
|
||||||
|
void ValidateRange(std::size_t file_size, std::size_t pos, std::size_t length) {
|
||||||
|
if (pos > file_size || length > file_size - pos) {
|
||||||
|
throw std::out_of_range("chunk or snapshot exceeds registered file size");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool FileState::RangeWritten(std::size_t pos, std::size_t length) const {
|
||||||
|
if (length == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const auto end = pos + length;
|
||||||
|
for (auto word = pos / kWordBits; word <= (end - 1) / kWordBits; ++word) {
|
||||||
|
const auto required = RangeMask(word, pos, end);
|
||||||
|
if ((written_[word] & required) != required) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<WordReservation> FileState::Reserve(std::size_t pos, std::size_t length) {
|
||||||
|
if (length == 0) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
const auto first = pos / kWordBits;
|
||||||
|
const auto last = (pos + length - 1) / kWordBits;
|
||||||
|
std::vector<WordReservation> reservations;
|
||||||
|
reservations.reserve(last - first + 1); // Allocation before changing any mask.
|
||||||
|
for (auto word = first; word <= last; ++word) {
|
||||||
|
const auto incoming = RangeMask(word, pos, pos + length);
|
||||||
|
const auto available = incoming & ~(written_[word] | in_progress_[word]);
|
||||||
|
if (available == 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
reservations.push_back({word, available});
|
||||||
|
in_progress_[word] |= available;
|
||||||
|
}
|
||||||
|
return reservations;
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileState::Commit(const std::vector<WordReservation>& reservations) noexcept {
|
||||||
|
for (const auto& reservation : reservations) {
|
||||||
|
written_[reservation.word_index] |= reservation.bits;
|
||||||
|
in_progress_[reservation.word_index] &= ~reservation.bits;
|
||||||
|
received_bytes_ += std::popcount(reservation.bits);
|
||||||
|
}
|
||||||
|
if (received_bytes_ == file_size_) {
|
||||||
|
ready_ = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileState::Rollback(const std::vector<WordReservation>& reservations) noexcept {
|
||||||
|
for (const auto& reservation : reservations) {
|
||||||
|
in_progress_[reservation.word_index] &= ~reservation.bits;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void FileState::Reset(
|
||||||
|
MutableFile fresh_data,
|
||||||
|
std::vector<std::uint64_t> fresh_written,
|
||||||
|
std::vector<std::uint64_t> fresh_in_progress) noexcept {
|
||||||
|
data_ = std::move(fresh_data);
|
||||||
|
written_ = std::move(fresh_written);
|
||||||
|
in_progress_ = std::move(fresh_in_progress);
|
||||||
|
received_bytes_ = 0;
|
||||||
|
error_ = nullptr;
|
||||||
|
ready_ = file_size_ == 0;
|
||||||
|
closing_ = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaitIdle(const FileState& state) noexcept {
|
||||||
|
auto pending = state.pending_tasks_.load(std::memory_order_acquire);
|
||||||
|
while (pending != 0) {
|
||||||
|
state.pending_tasks_.wait(pending, std::memory_order_acquire);
|
||||||
|
pending = state.pending_tasks_.load(std::memory_order_acquire);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void CompleteTask(FileState& state) noexcept {
|
||||||
|
state.pending_tasks_.fetch_sub(1, std::memory_order_release);
|
||||||
|
state.pending_tasks_.notify_all();
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace file_collector::detail
|
||||||
|
|
||||||
51
src/file_state.hpp
Normal file
51
src/file_state.hpp
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "file_collector/i_file_collector.hpp"
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <exception>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace file_collector::detail {
|
||||||
|
|
||||||
|
struct WordReservation {
|
||||||
|
std::size_t word_index;
|
||||||
|
std::uint64_t bits;
|
||||||
|
};
|
||||||
|
|
||||||
|
class FileState final {
|
||||||
|
public:
|
||||||
|
explicit FileState(std::size_t file_size);
|
||||||
|
|
||||||
|
[[nodiscard]] bool RangeWritten(std::size_t pos, std::size_t length) const;
|
||||||
|
[[nodiscard]] std::vector<WordReservation> Reserve(std::size_t pos, std::size_t length);
|
||||||
|
void Commit(const std::vector<WordReservation>& reservations) noexcept;
|
||||||
|
void Rollback(const std::vector<WordReservation>& reservations) noexcept;
|
||||||
|
void Reset(MutableFile fresh_data,
|
||||||
|
std::vector<std::uint64_t> fresh_written,
|
||||||
|
std::vector<std::uint64_t> fresh_in_progress) noexcept;
|
||||||
|
|
||||||
|
std::mutex mutex_;
|
||||||
|
std::mutex lifecycle_mutex_;
|
||||||
|
MutableFile data_;
|
||||||
|
std::vector<std::uint64_t> written_;
|
||||||
|
std::vector<std::uint64_t> in_progress_;
|
||||||
|
std::size_t file_size_;
|
||||||
|
std::size_t received_bytes_ = 0;
|
||||||
|
std::atomic_size_t pending_tasks_{0};
|
||||||
|
std::exception_ptr error_;
|
||||||
|
bool ready_;
|
||||||
|
bool closing_ = false;
|
||||||
|
bool removed_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
void WaitIdle(const FileState& state) noexcept;
|
||||||
|
void CompleteTask(FileState& state) noexcept;
|
||||||
|
void ValidateRange(std::size_t file_size, std::size_t pos, std::size_t length);
|
||||||
|
|
||||||
|
} // namespace file_collector::detail
|
||||||
|
|
||||||
52
src/thread_pool.cpp
Normal file
52
src/thread_pool.cpp
Normal file
|
|
@ -0,0 +1,52 @@
|
||||||
|
#include "thread_pool.hpp"
|
||||||
|
|
||||||
|
namespace file_collector::detail {
|
||||||
|
|
||||||
|
ThreadPool::ThreadPool(std::size_t worker_count) {
|
||||||
|
const auto count = worker_count == 0 ? std::size_t{1} : worker_count;
|
||||||
|
workers_.reserve(count);
|
||||||
|
try {
|
||||||
|
for (std::size_t i = 0; i < count; ++i) {
|
||||||
|
workers_.emplace_back([this] { Run(); });
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
{
|
||||||
|
std::lock_guard lock(mutex_);
|
||||||
|
stopping_ = true;
|
||||||
|
}
|
||||||
|
condition_.notify_all();
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ThreadPool::~ThreadPool() {
|
||||||
|
{
|
||||||
|
std::lock_guard lock(mutex_);
|
||||||
|
stopping_ = true;
|
||||||
|
}
|
||||||
|
condition_.notify_all();
|
||||||
|
// jthread destruction joins every worker, after all accepted tasks drain.
|
||||||
|
}
|
||||||
|
|
||||||
|
std::size_t ThreadPool::WorkerCount() const noexcept {
|
||||||
|
return workers_.size();
|
||||||
|
}
|
||||||
|
|
||||||
|
void ThreadPool::Run() {
|
||||||
|
for (;;) {
|
||||||
|
std::packaged_task<void()> task;
|
||||||
|
{
|
||||||
|
std::unique_lock lock(mutex_);
|
||||||
|
condition_.wait(lock, [this] { return stopping_ || !queue_.empty(); });
|
||||||
|
if (queue_.empty() && stopping_) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
task = std::move(queue_.front());
|
||||||
|
queue_.pop_front();
|
||||||
|
}
|
||||||
|
task(); // packaged_task captures task exceptions, keeping workers alive.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace file_collector::detail
|
||||||
|
|
||||||
48
src/thread_pool.hpp
Normal file
48
src/thread_pool.hpp
Normal file
|
|
@ -0,0 +1,48 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <condition_variable>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <deque>
|
||||||
|
#include <future>
|
||||||
|
#include <mutex>
|
||||||
|
#include <stdexcept>
|
||||||
|
#include <thread>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace file_collector::detail {
|
||||||
|
|
||||||
|
class ThreadPool final {
|
||||||
|
public:
|
||||||
|
explicit ThreadPool(std::size_t worker_count = std::thread::hardware_concurrency());
|
||||||
|
~ThreadPool();
|
||||||
|
ThreadPool(const ThreadPool&) = delete;
|
||||||
|
ThreadPool& operator=(const ThreadPool&) = delete;
|
||||||
|
|
||||||
|
[[nodiscard]] std::size_t WorkerCount() const noexcept;
|
||||||
|
|
||||||
|
template <class Task>
|
||||||
|
void Submit(Task&& task) {
|
||||||
|
std::packaged_task<void()> packaged(std::forward<Task>(task));
|
||||||
|
{
|
||||||
|
std::lock_guard lock(mutex_);
|
||||||
|
if (stopping_) {
|
||||||
|
throw std::runtime_error("thread pool is stopping");
|
||||||
|
}
|
||||||
|
queue_.push_back(std::move(packaged));
|
||||||
|
}
|
||||||
|
condition_.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
void Run();
|
||||||
|
|
||||||
|
std::mutex mutex_;
|
||||||
|
std::condition_variable condition_;
|
||||||
|
std::deque<std::packaged_task<void()>> queue_;
|
||||||
|
std::vector<std::jthread> workers_;
|
||||||
|
bool stopping_ = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace file_collector::detail
|
||||||
|
|
||||||
38
tests/CMakeLists.txt
Normal file
38
tests/CMakeLists.txt
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
find_package(GTest CONFIG QUIET)
|
||||||
|
|
||||||
|
if(NOT GTest_FOUND)
|
||||||
|
include(FetchContent)
|
||||||
|
set(FILE_COLLECTOR_GTEST_SOURCE_DIR "" CACHE PATH "Existing local googletest source checkout")
|
||||||
|
if(FILE_COLLECTOR_GTEST_SOURCE_DIR)
|
||||||
|
add_subdirectory("${FILE_COLLECTOR_GTEST_SOURCE_DIR}"
|
||||||
|
"${CMAKE_CURRENT_BINARY_DIR}/googletest" EXCLUDE_FROM_ALL)
|
||||||
|
else()
|
||||||
|
FetchContent_Declare(googletest
|
||||||
|
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
|
||||||
|
)
|
||||||
|
FetchContent_MakeAvailable(googletest)
|
||||||
|
endif()
|
||||||
|
endif()
|
||||||
|
|
||||||
|
add_executable(file_collector_tests
|
||||||
|
collector_tests.cpp
|
||||||
|
chunk_tests.cpp
|
||||||
|
boundary_tests.cpp
|
||||||
|
concurrency_tests.cpp
|
||||||
|
lifecycle_tests.cpp
|
||||||
|
snapshot_tests.cpp
|
||||||
|
exception_tests.cpp
|
||||||
|
thread_pool_tests.cpp
|
||||||
|
stress_tests.cpp
|
||||||
|
performance_tests.cpp
|
||||||
|
)
|
||||||
|
target_include_directories(file_collector_tests PRIVATE "${PROJECT_SOURCE_DIR}/src")
|
||||||
|
target_link_libraries(file_collector_tests PRIVATE file_collector GTest::gtest_main Threads::Threads)
|
||||||
|
|
||||||
|
include(GoogleTest)
|
||||||
|
gtest_discover_tests(file_collector_tests
|
||||||
|
DISCOVERY_MODE PRE_TEST
|
||||||
|
DISCOVERY_TIMEOUT 60
|
||||||
|
PROPERTIES TIMEOUT 120
|
||||||
|
)
|
||||||
|
|
||||||
45
tests/boundary_tests.cpp
Normal file
45
tests/boundary_tests.cpp
Normal file
|
|
@ -0,0 +1,45 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <limits>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
TEST(Boundary, UnknownIdRejectedEverywhere) {
|
||||||
|
FileCollector collector(1);
|
||||||
|
EXPECT_THROW(collector.OnNewChunk(99, 0, {}), std::out_of_range);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(99)), std::out_of_range);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(99, 0, 0)), std::out_of_range);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.TakeFile(99)), std::out_of_range);
|
||||||
|
EXPECT_THROW(collector.RemoveFile(99), std::out_of_range);
|
||||||
|
EXPECT_THROW(collector.ClearFile(99), std::out_of_range);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Boundary, OffsetsCheckedWithoutOverflow) {
|
||||||
|
FileCollector collector(1);
|
||||||
|
collector.CollectFile(1, 4);
|
||||||
|
EXPECT_THROW(collector.OnNewChunk(1, 5, {}), std::out_of_range);
|
||||||
|
EXPECT_THROW(collector.OnNewChunk(1, 3, FileBytes{1, 2}), std::out_of_range);
|
||||||
|
EXPECT_THROW(collector.OnNewChunk(1, std::numeric_limits<std::size_t>::max(), {}), std::out_of_range);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1, 3, 2, false)), std::out_of_range);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1, 5, 0, false)), std::out_of_range);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1, std::numeric_limits<std::size_t>::max(), 1, false)), std::out_of_range);
|
||||||
|
EXPECT_EQ(collector.GetFile(1, 4, 0)->size(), std::size_t{0});
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Boundary, DuplicateRegistrationRejectedUntilRemoved) {
|
||||||
|
FileCollector collector(1);
|
||||||
|
collector.CollectFile(1, 1);
|
||||||
|
EXPECT_THROW(collector.CollectFile(1, 9), std::logic_error);
|
||||||
|
collector.RemoveFile(1);
|
||||||
|
EXPECT_NO_THROW(collector.CollectFile(1, 9));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Boundary, EmptyChunkIsNoopExceptReady) {
|
||||||
|
FileCollector collector(1);
|
||||||
|
collector.CollectFile(1, 2);
|
||||||
|
collector.OnNewChunk(1, 2, {});
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1)), std::logic_error);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{3, 4});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes{3, 4}));
|
||||||
|
}
|
||||||
|
|
||||||
51
tests/chunk_tests.cpp
Normal file
51
tests/chunk_tests.cpp
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
TEST(Chunks, OutOfOrderAndPartialOverlap) {
|
||||||
|
FileCollector collector(3);
|
||||||
|
collector.CollectFile(7, 10);
|
||||||
|
collector.OnNewChunk(7, 6, FileBytes{'G', 'H', 'I', 'J'});
|
||||||
|
collector.OnNewChunk(7, 2, FileBytes{'C', 'D', 'E', 'F'});
|
||||||
|
collector.OnNewChunk(7, 0, FileBytes{'A', 'B', 'C', 'D'});
|
||||||
|
EXPECT_EQ(*collector.GetFile(7), (FileBytes{'A','B','C','D','E','F','G','H','I','J'}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Chunks, DuplicatesAndContainedOverlaps) {
|
||||||
|
FileCollector collector(4);
|
||||||
|
auto original = test_data::Pattern(127);
|
||||||
|
collector.CollectFile(1, original.size());
|
||||||
|
collector.OnNewChunk(1, 0, test_data::Slice(original, 0, 80));
|
||||||
|
collector.OnNewChunk(1, 12, test_data::Slice(original, 12, 30));
|
||||||
|
collector.OnNewChunk(1, 63, test_data::Slice(original, 63, 64));
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes(original));
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), original);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes(original)); // ready: ignore without requeue
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), original);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Chunks, WordBoundaries63_64_65) {
|
||||||
|
for (std::size_t size : {std::size_t{1}, std::size_t{63}, std::size_t{64},
|
||||||
|
std::size_t{65}, std::size_t{129}}) {
|
||||||
|
SCOPED_TRACE(size);
|
||||||
|
FileCollector collector(2);
|
||||||
|
auto original = test_data::Pattern(size);
|
||||||
|
collector.CollectFile(1, size);
|
||||||
|
for (std::size_t i = size; i-- > 0;) {
|
||||||
|
collector.OnNewChunk(1, i, FileBytes{original[i]});
|
||||||
|
}
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Chunks, OriginalZeroBytesAreNotHoles) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 5);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{0, 0, 0});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1, 0, 3), (FileBytes{0, 0, 0}));
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1, 0, 4)), std::logic_error);
|
||||||
|
collector.OnNewChunk(1, 3, FileBytes{0, 0});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes(5, 0)));
|
||||||
|
}
|
||||||
|
|
||||||
53
tests/collector_tests.cpp
Normal file
53
tests/collector_tests.cpp
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <memory>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
static_assert(std::is_same_v<decltype(std::declval<IFileCollector&>().GetFile(0)), FileView>);
|
||||||
|
static_assert(std::is_same_v<decltype(std::declval<IFileCollector&>().GetFile(0, 0, 0)), FileView>);
|
||||||
|
static_assert(std::is_same_v<decltype(std::declval<IFileCollector&>().TakeFile(0)), MutableFile>);
|
||||||
|
|
||||||
|
TEST(Collector, PolymorphicInterfaceAndIndependentFiles) {
|
||||||
|
std::unique_ptr<IFileCollector> collector = std::make_unique<FileCollector>(2);
|
||||||
|
const FileBytes one{1, 2, 3};
|
||||||
|
const FileBytes two{4, 5};
|
||||||
|
collector->CollectFile(17, one.size());
|
||||||
|
collector->CollectFile(18, two.size());
|
||||||
|
collector->OnNewChunk(18, 0, FileBytes(two));
|
||||||
|
collector->OnNewChunk(17, 0, FileBytes(one));
|
||||||
|
EXPECT_EQ(*collector->GetFile(17), one);
|
||||||
|
EXPECT_EQ(*collector->GetFile(18), two);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Collector, ZeroLengthReadyImmediately) {
|
||||||
|
FileCollector collector(1);
|
||||||
|
collector.CollectFile(1, 0);
|
||||||
|
EXPECT_TRUE(collector.GetFile(1)->empty());
|
||||||
|
EXPECT_TRUE(collector.GetFile(1, 0, 0)->empty());
|
||||||
|
collector.OnNewChunk(1, 0, {});
|
||||||
|
EXPECT_TRUE(collector.TakeFile(1)->empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Collector, IncompleteFileNeedsExplicitOptOut) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 5);
|
||||||
|
collector.OnNewChunk(1, 1, FileBytes{7, 8});
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1)), std::logic_error);
|
||||||
|
EXPECT_EQ(*collector.GetFile(1, false), (FileBytes{0, 7, 8, 0, 0}));
|
||||||
|
EXPECT_EQ(*collector.GetFile(1, 1, 2), (FileBytes{7, 8}));
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1, 0, 3)), std::logic_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Collector, TakeIncompleteOnlyWhenCheckingDisabled) {
|
||||||
|
FileCollector collector(1);
|
||||||
|
collector.CollectFile(1, 3);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1});
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.TakeFile(1)), std::logic_error);
|
||||||
|
collector.OnNewChunk(1, 2, FileBytes{3});
|
||||||
|
auto bytes = collector.TakeFile(1, false);
|
||||||
|
EXPECT_EQ(*bytes, (FileBytes{1, 0, 3}));
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1)), std::out_of_range);
|
||||||
|
}
|
||||||
|
|
||||||
72
tests/concurrency_tests.cpp
Normal file
72
tests/concurrency_tests.cpp
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <barrier>
|
||||||
|
#include <exception>
|
||||||
|
#include <mutex>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
TEST(Concurrency, ConcurrentDisjointWritesToOneFile) {
|
||||||
|
constexpr std::size_t parts = 8;
|
||||||
|
constexpr std::size_t bytes_per_part = 4096;
|
||||||
|
FileCollector collector(4);
|
||||||
|
auto original = test_data::Pattern(parts * bytes_per_part);
|
||||||
|
collector.CollectFile(1, original.size());
|
||||||
|
std::barrier start(static_cast<std::ptrdiff_t>(parts));
|
||||||
|
std::vector<std::jthread> producers;
|
||||||
|
for (std::size_t part = 0; part < parts; ++part) {
|
||||||
|
producers.emplace_back([&, part] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
const auto pos = part * bytes_per_part;
|
||||||
|
collector.OnNewChunk(1, pos, test_data::Slice(original, pos, bytes_per_part));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
producers.clear(); // jthread joins
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), original);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Concurrency, ManyProducersOverlappingIdenticalData) {
|
||||||
|
constexpr std::size_t producers_count = 8;
|
||||||
|
FileCollector collector(4);
|
||||||
|
auto original = test_data::Pattern(8192);
|
||||||
|
collector.CollectFile(10, original.size());
|
||||||
|
std::barrier start(static_cast<std::ptrdiff_t>(producers_count));
|
||||||
|
std::vector<std::jthread> producers;
|
||||||
|
for (std::size_t i = 0; i < producers_count; ++i) {
|
||||||
|
producers.emplace_back([&, i] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
for (std::size_t pos = i * 97 % 512; pos < original.size(); pos += 4096) {
|
||||||
|
const auto count = std::min<std::size_t>(5000, original.size() - pos);
|
||||||
|
collector.OnNewChunk(10, pos, test_data::Slice(original, pos, count));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
producers.clear();
|
||||||
|
collector.OnNewChunk(10, 0, FileBytes(original));
|
||||||
|
EXPECT_EQ(*collector.GetFile(10), original);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Concurrency, SeveralFilesRemainIndependent) {
|
||||||
|
FileCollector collector(4);
|
||||||
|
std::vector<FileBytes> originals;
|
||||||
|
for (std::uint32_t id = 0; id < 6; ++id) {
|
||||||
|
originals.push_back(test_data::Pattern(4096, 400 + id));
|
||||||
|
collector.CollectFile(id, 4096);
|
||||||
|
}
|
||||||
|
std::barrier start(6);
|
||||||
|
std::vector<std::jthread> producers;
|
||||||
|
for (std::uint32_t id = 0; id < 6; ++id) {
|
||||||
|
producers.emplace_back([&, id] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
collector.OnNewChunk(id, 2048, test_data::Slice(originals[id], 2048, 2048));
|
||||||
|
collector.OnNewChunk(id, 0, test_data::Slice(originals[id], 0, 2048));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
producers.clear();
|
||||||
|
for (std::uint32_t id = 0; id < 6; ++id) {
|
||||||
|
EXPECT_EQ(*collector.GetFile(id), originals[id]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
112
tests/exception_tests.cpp
Normal file
112
tests/exception_tests.cpp
Normal file
|
|
@ -0,0 +1,112 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include "fault_injector.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <atomic>
|
||||||
|
#include <latch>
|
||||||
|
#include <stdexcept>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
class OneShotFault final : public detail::FaultInjector {
|
||||||
|
public:
|
||||||
|
explicit OneShotFault(detail::FaultPoint target) : target_(target) {}
|
||||||
|
|
||||||
|
void Hit(detail::FaultPoint point) override {
|
||||||
|
if (point == target_ && !triggered_.exchange(true)) {
|
||||||
|
throw std::runtime_error("injected failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private:
|
||||||
|
detail::FaultPoint target_;
|
||||||
|
std::atomic_bool triggered_{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
class GatedFailure final : public detail::FaultInjector {
|
||||||
|
public:
|
||||||
|
void Hit(detail::FaultPoint point) override {
|
||||||
|
if (point == detail::FaultPoint::AfterReserve && !hit_.exchange(true)) {
|
||||||
|
reached_.count_down();
|
||||||
|
resume_.wait();
|
||||||
|
throw std::runtime_error("gated injected failure");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void WaitUntilReserved() { reached_.wait(); }
|
||||||
|
void Release() { resume_.count_down(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::atomic_bool hit_{false};
|
||||||
|
std::latch reached_{1};
|
||||||
|
std::latch resume_{1};
|
||||||
|
};
|
||||||
|
|
||||||
|
class CountSubmissions final : public detail::FaultInjector {
|
||||||
|
public:
|
||||||
|
void Hit(detail::FaultPoint point) override {
|
||||||
|
if (point == detail::FaultPoint::BeforeEnqueue) {
|
||||||
|
count_.fetch_add(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[[nodiscard]] int Count() const noexcept { return count_.load(); }
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::atomic_int count_{0};
|
||||||
|
};
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(Exceptions, BeforeEnqueueFailureRollsBackPendingCounter) {
|
||||||
|
auto injector = std::make_shared<OneShotFault>(detail::FaultPoint::BeforeEnqueue);
|
||||||
|
FileCollector collector(2, injector);
|
||||||
|
collector.CollectFile(1, 3);
|
||||||
|
EXPECT_THROW(collector.OnNewChunk(1, 0, FileBytes{1, 2, 3}), std::runtime_error);
|
||||||
|
EXPECT_EQ(*collector.GetFile(1, false), (FileBytes{0, 0, 0}));
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2, 3});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes{1, 2, 3}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Exceptions, AllWorkerFaultPointsReportAndRecoverAfterClear) {
|
||||||
|
for (auto point : {detail::FaultPoint::AfterReserve,
|
||||||
|
detail::FaultPoint::BeforeCopy,
|
||||||
|
detail::FaultPoint::BeforeCommit}) {
|
||||||
|
SCOPED_TRACE(static_cast<int>(point));
|
||||||
|
auto injector = std::make_shared<OneShotFault>(point);
|
||||||
|
FileCollector collector(2, injector);
|
||||||
|
collector.CollectFile(1, 65);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes(65, 7));
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1, false)), std::runtime_error);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.TakeFile(1)), std::runtime_error);
|
||||||
|
collector.ClearFile(1);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes(65, 9));
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes(65, 9)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Exceptions, FailedReservationCannotLeavePhantomCoverage) {
|
||||||
|
auto injector = std::make_shared<GatedFailure>();
|
||||||
|
FileCollector collector(2, injector);
|
||||||
|
collector.CollectFile(7, 64);
|
||||||
|
collector.OnNewChunk(7, 0, FileBytes(64, 42));
|
||||||
|
injector->WaitUntilReserved();
|
||||||
|
collector.OnNewChunk(7, 0, FileBytes(64, 42));
|
||||||
|
injector->Release();
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(7)), std::runtime_error);
|
||||||
|
collector.ClearFile(7);
|
||||||
|
collector.OnNewChunk(7, 0, FileBytes(64, 33));
|
||||||
|
EXPECT_EQ(*collector.GetFile(7), (FileBytes(64, 33)));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Exceptions, CompletedFileDoesNotEnqueueNewChunks) {
|
||||||
|
auto injector = std::make_shared<CountSubmissions>();
|
||||||
|
FileCollector collector(2, injector);
|
||||||
|
collector.CollectFile(1, 3);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2, 3});
|
||||||
|
ASSERT_EQ(*collector.GetFile(1), (FileBytes{1, 2, 3}));
|
||||||
|
const auto initial_submissions = injector->Count();
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2, 3});
|
||||||
|
EXPECT_EQ(injector->Count(), initial_submissions);
|
||||||
|
}
|
||||||
|
|
||||||
64
tests/lifecycle_tests.cpp
Normal file
64
tests/lifecycle_tests.cpp
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <barrier>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
TEST(Lifecycle, TakeTransfersMutableBufferAndAllowsRegistration) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 3);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{4, 5, 6});
|
||||||
|
MutableFile bytes = collector.TakeFile(1);
|
||||||
|
EXPECT_EQ(*bytes, (FileBytes{4, 5, 6}));
|
||||||
|
bytes->at(0) = 99;
|
||||||
|
EXPECT_EQ(bytes->front(), 99);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1)), std::out_of_range);
|
||||||
|
collector.CollectFile(1, 1);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{7});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes{7}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Lifecycle, ClearKeepsRegistrationAndSize) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 4);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2, 3, 4});
|
||||||
|
auto previous = collector.GetFile(1);
|
||||||
|
collector.ClearFile(1);
|
||||||
|
EXPECT_THROW(static_cast<void>(collector.GetFile(1)), std::logic_error);
|
||||||
|
EXPECT_EQ(*collector.GetFile(1, false), (FileBytes{0, 0, 0, 0}));
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{5, 6, 7, 8});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes{5, 6, 7, 8}));
|
||||||
|
EXPECT_EQ(*previous, (FileBytes{1, 2, 3, 4}));
|
||||||
|
EXPECT_THROW(collector.CollectFile(1, 1), std::logic_error);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Lifecycle, RemovalDoesNotInvalidateView) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 2);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{3, 4});
|
||||||
|
auto previous = collector.GetFile(1);
|
||||||
|
collector.RemoveFile(1);
|
||||||
|
EXPECT_EQ(*previous, (FileBytes{3, 4}));
|
||||||
|
collector.CollectFile(1, 2);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{5, 6});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes{5, 6}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Lifecycle, ConcurrentClearAndSubmissionRemainReusable) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 64);
|
||||||
|
std::barrier start(2);
|
||||||
|
std::jthread sender([&] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
try { collector.OnNewChunk(1, 0, FileBytes(64, 8)); }
|
||||||
|
catch (const std::logic_error&) {} // Clear may close admission first.
|
||||||
|
});
|
||||||
|
start.arrive_and_wait();
|
||||||
|
collector.ClearFile(1);
|
||||||
|
sender.join();
|
||||||
|
collector.ClearFile(1);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes(64, 9));
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes(64, 9)));
|
||||||
|
}
|
||||||
|
|
||||||
68
tests/performance_tests.cpp
Normal file
68
tests/performance_tests.cpp
Normal file
|
|
@ -0,0 +1,68 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <iostream>
|
||||||
|
#include <numeric>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
#if defined(__APPLE__) || defined(__linux__)
|
||||||
|
#include <sys/resource.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
double PeakMiB() {
|
||||||
|
#if defined(__APPLE__) || defined(__linux__)
|
||||||
|
rusage usage{};
|
||||||
|
if (getrusage(RUSAGE_SELF, &usage) == 0) {
|
||||||
|
#if defined(__APPLE__)
|
||||||
|
return static_cast<double>(usage.ru_maxrss) / (1024.0 * 1024.0);
|
||||||
|
#else
|
||||||
|
return static_cast<double>(usage.ru_maxrss) / 1024.0;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
return -1.;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(Performance, BaselineMiBPerSecondAndSubmissionLatency) {
|
||||||
|
using Clock = std::chrono::steady_clock;
|
||||||
|
constexpr std::size_t size = 4 * 1024 * 1024;
|
||||||
|
constexpr std::size_t chunk_size = 16 * 1024;
|
||||||
|
auto original = test_data::Pattern(size, 1001);
|
||||||
|
FileCollector collector(4);
|
||||||
|
collector.CollectFile(1, size);
|
||||||
|
std::vector<double> submit_microseconds;
|
||||||
|
submit_microseconds.reserve(size / chunk_size);
|
||||||
|
const auto start = Clock::now();
|
||||||
|
for (std::size_t pos = 0; pos < size; pos += chunk_size) {
|
||||||
|
auto chunk = test_data::Slice(original, pos, chunk_size);
|
||||||
|
const auto t0 = Clock::now();
|
||||||
|
collector.OnNewChunk(1, pos, std::move(chunk));
|
||||||
|
submit_microseconds.push_back(std::chrono::duration<double, std::micro>(Clock::now() - t0).count());
|
||||||
|
}
|
||||||
|
auto restored = collector.GetFile(1);
|
||||||
|
const auto elapsed = std::chrono::duration<double>(Clock::now() - start).count();
|
||||||
|
ASSERT_EQ(*restored, original);
|
||||||
|
std::sort(submit_microseconds.begin(), submit_microseconds.end());
|
||||||
|
const auto percentile = [&](double fraction) {
|
||||||
|
const auto index = static_cast<std::size_t>((submit_microseconds.size() - 1) * fraction);
|
||||||
|
return submit_microseconds[index];
|
||||||
|
};
|
||||||
|
std::cout << std::fixed << std::setprecision(2)
|
||||||
|
<< "profile: size_mib=4 chunk_kib=16 workers=4 seed=1001"
|
||||||
|
<< " throughput_mib_s=" << 4.0 / elapsed
|
||||||
|
<< " submission_p50_us=" << percentile(0.50)
|
||||||
|
<< " submission_p95_us=" << percentile(0.95)
|
||||||
|
<< " peak_process_rss_mib=" << PeakMiB()
|
||||||
|
<< " duplicate_fraction=0" << '\n';
|
||||||
|
// Metrics are informational, with no machine-specific timing thresholds.
|
||||||
|
}
|
||||||
|
|
||||||
55
tests/snapshot_tests.cpp
Normal file
55
tests/snapshot_tests.cpp
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
TEST(Snapshots, PartialAndIncompleteCopiesNeverChange) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 5);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2});
|
||||||
|
auto incomplete = collector.GetFile(1, false);
|
||||||
|
auto partial = collector.GetFile(1, 0, 4, false);
|
||||||
|
collector.OnNewChunk(1, 2, FileBytes{3, 4, 5});
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), (FileBytes{1, 2, 3, 4, 5}));
|
||||||
|
EXPECT_EQ(*incomplete, (FileBytes{1, 2, 0, 0, 0}));
|
||||||
|
EXPECT_EQ(*partial, (FileBytes{1, 2, 0, 0}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Snapshots, ReadyFileUsesSharedReadOnlyBacking) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 3);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2, 3});
|
||||||
|
auto first = collector.GetFile(1);
|
||||||
|
auto second = collector.GetFile(1);
|
||||||
|
EXPECT_EQ(first.get(), second.get());
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{99});
|
||||||
|
EXPECT_EQ(*first, (FileBytes{1, 2, 3}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Snapshots, TakeCopiesWhenReadOnlyOwnerExists) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 3);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2, 3});
|
||||||
|
auto read_only = collector.GetFile(1);
|
||||||
|
auto writable = collector.TakeFile(1);
|
||||||
|
EXPECT_NE(read_only.get(), writable.get());
|
||||||
|
writable->at(1) = 99;
|
||||||
|
EXPECT_EQ(*read_only, (FileBytes{1, 2, 3}));
|
||||||
|
EXPECT_EQ(*writable, (FileBytes{1, 99, 3}));
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Snapshots, ClearAndReregisterPreservePreviouslyIssuedViews) {
|
||||||
|
FileCollector collector(2);
|
||||||
|
collector.CollectFile(1, 2);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{1, 2});
|
||||||
|
auto old_view = collector.GetFile(1);
|
||||||
|
collector.ClearFile(1);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{3, 4});
|
||||||
|
auto mid_view = collector.GetFile(1);
|
||||||
|
collector.RemoveFile(1);
|
||||||
|
collector.CollectFile(1, 1);
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes{5});
|
||||||
|
EXPECT_EQ(*old_view, (FileBytes{1, 2}));
|
||||||
|
EXPECT_EQ(*mid_view, (FileBytes{3, 4}));
|
||||||
|
}
|
||||||
|
|
||||||
207
tests/stress_tests.cpp
Normal file
207
tests/stress_tests.cpp
Normal file
|
|
@ -0,0 +1,207 @@
|
||||||
|
#include "test_data.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <barrier>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <exception>
|
||||||
|
#include <random>
|
||||||
|
#include <thread>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
struct Chunk {
|
||||||
|
std::size_t pos;
|
||||||
|
FileBytes bytes;
|
||||||
|
};
|
||||||
|
|
||||||
|
std::vector<Chunk> MakeChunks(const FileBytes& original, std::uint32_t seed) {
|
||||||
|
std::mt19937 rng(seed);
|
||||||
|
std::vector<Chunk> chunks;
|
||||||
|
for (std::size_t pos = 0; pos < original.size(); pos += 193) {
|
||||||
|
const std::size_t length = std::min<std::size_t>(257, original.size() - pos);
|
||||||
|
chunks.push_back({pos, test_data::Slice(original, pos, length)});
|
||||||
|
if (rng() % 3 == 0) {
|
||||||
|
chunks.push_back({pos, test_data::Slice(original, pos, length)});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::shuffle(chunks.begin(), chunks.end(), rng);
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<Chunk> MakeRandomOverlappingChunks(const FileBytes& original, std::uint32_t seed) {
|
||||||
|
std::mt19937 rng(seed);
|
||||||
|
std::vector<Chunk> chunks;
|
||||||
|
if (original.empty()) {
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A randomized partition guarantees complete coverage independently of overlaps.
|
||||||
|
for (std::size_t pos = 0; pos < original.size();) {
|
||||||
|
const auto maximum = std::min<std::size_t>(4096, original.size() - pos);
|
||||||
|
const auto length = std::uniform_int_distribution<std::size_t>(1, maximum)(rng);
|
||||||
|
chunks.push_back({pos, test_data::Slice(original, pos, length)});
|
||||||
|
if (rng() % 5 == 0) {
|
||||||
|
chunks.push_back(chunks.back()); // Full duplicate.
|
||||||
|
}
|
||||||
|
pos += length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Independent random windows create additional arbitrary partial overlaps.
|
||||||
|
const auto windows = std::min<std::size_t>(4096, original.size() / 31 + 25);
|
||||||
|
for (std::size_t i = 0; i < windows; ++i) {
|
||||||
|
const auto maximum = std::min<std::size_t>(8192, original.size());
|
||||||
|
const auto length = std::uniform_int_distribution<std::size_t>(1, maximum)(rng);
|
||||||
|
const auto pos = std::uniform_int_distribution<std::size_t>(0, original.size() - length)(rng);
|
||||||
|
chunks.push_back({pos, test_data::Slice(original, pos, length)});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Explicitly guarantee 1-byte, weak, medium, heavy and full intersections.
|
||||||
|
if (original.size() >= 4096) {
|
||||||
|
constexpr std::size_t anchor_length = 1024;
|
||||||
|
const auto anchor = std::uniform_int_distribution<std::size_t>(
|
||||||
|
0, original.size() - 2 * anchor_length)(rng);
|
||||||
|
chunks.push_back({anchor, test_data::Slice(original, anchor, anchor_length)});
|
||||||
|
for (const auto overlap : std::array<std::size_t, 8>{1, 102, 256, 512, 768, 922, 1023, 1024}) {
|
||||||
|
const auto pos = anchor + anchor_length - overlap;
|
||||||
|
chunks.push_back({pos, test_data::Slice(original, pos, anchor_length)});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
std::shuffle(chunks.begin(), chunks.end(), rng);
|
||||||
|
return chunks;
|
||||||
|
}
|
||||||
|
|
||||||
|
void SubmitRandomChunks(FileCollector& collector, const std::vector<Chunk>& chunks,
|
||||||
|
std::uint32_t file_id, std::size_t producers_count) {
|
||||||
|
std::barrier start(static_cast<std::ptrdiff_t>(producers_count));
|
||||||
|
std::vector<std::exception_ptr> errors(producers_count);
|
||||||
|
std::vector<std::jthread> producers;
|
||||||
|
for (std::size_t producer = 0; producer < producers_count; ++producer) {
|
||||||
|
producers.emplace_back([&, producer] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
try {
|
||||||
|
for (std::size_t index = producer; index < chunks.size(); index += producers_count) {
|
||||||
|
collector.OnNewChunk(file_id, chunks[index].pos, FileBytes(chunks[index].bytes));
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
errors[producer] = std::current_exception();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
producers.clear(); // Join all producers before propagating errors.
|
||||||
|
for (const auto& error : errors) {
|
||||||
|
if (error) {
|
||||||
|
std::rethrow_exception(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
TEST(Stress, DeterministicMultiProducerOverlaps) {
|
||||||
|
constexpr std::size_t file_size = 1024 * 1024;
|
||||||
|
for (std::uint32_t seed : {101u, 202u, 303u}) {
|
||||||
|
SCOPED_TRACE(seed);
|
||||||
|
auto original = test_data::Pattern(file_size, seed);
|
||||||
|
auto chunks = MakeChunks(original, seed);
|
||||||
|
FileCollector collector(4);
|
||||||
|
collector.CollectFile(1, file_size);
|
||||||
|
std::barrier start(8);
|
||||||
|
std::vector<std::jthread> senders;
|
||||||
|
for (std::size_t worker = 0; worker < 8; ++worker) {
|
||||||
|
senders.emplace_back([&, worker] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
for (std::size_t index = worker; index < chunks.size(); index += 8) {
|
||||||
|
collector.OnNewChunk(1, chunks[index].pos, FileBytes(chunks[index].bytes));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
senders.clear();
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Stress, ThousandsOfRepeatedOverlaps) {
|
||||||
|
auto original = test_data::Pattern(8193, 77);
|
||||||
|
FileCollector collector(4);
|
||||||
|
collector.CollectFile(1, original.size());
|
||||||
|
for (int repeat = 0; repeat < 2000; ++repeat) {
|
||||||
|
const std::size_t pos = static_cast<std::size_t>(repeat * 31) % (original.size() - 128);
|
||||||
|
collector.OnNewChunk(1, pos, test_data::Slice(original, pos, 128));
|
||||||
|
}
|
||||||
|
collector.OnNewChunk(1, 0, FileBytes(original));
|
||||||
|
EXPECT_EQ(*collector.GetFile(1), original);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Stress, RandomizedOverlapSpectrumAcrossSizesAndSeeds) {
|
||||||
|
constexpr std::array<std::size_t, 8> file_sizes{0, 1, 63, 64, 65, 4096, 65537, 1048576};
|
||||||
|
constexpr std::array<std::uint32_t, 4> seeds{7, 101, 2026, 0xC0FFEE};
|
||||||
|
for (const auto file_size : file_sizes) {
|
||||||
|
for (const auto seed : seeds) {
|
||||||
|
SCOPED_TRACE(::testing::Message() << "size=" << file_size << " seed=" << seed);
|
||||||
|
const auto original = test_data::Pattern(file_size, seed);
|
||||||
|
const auto chunks = MakeRandomOverlappingChunks(original, seed);
|
||||||
|
FileCollector collector(4);
|
||||||
|
collector.CollectFile(77, file_size);
|
||||||
|
SubmitRandomChunks(collector, chunks, 77, 8);
|
||||||
|
EXPECT_EQ(*collector.GetFile(77), original);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(Stress, RandomizedSnapshotsStayImmutableDuringConcurrentIngestion) {
|
||||||
|
constexpr std::size_t file_size = 65537;
|
||||||
|
auto original = test_data::Pattern(file_size, 0xBADC0DE);
|
||||||
|
auto chunks = MakeRandomOverlappingChunks(original, 0xBADC0DE);
|
||||||
|
FileCollector collector(4);
|
||||||
|
collector.CollectFile(21, file_size);
|
||||||
|
const auto initial_snapshot = collector.GetFile(21, false);
|
||||||
|
EXPECT_EQ(*initial_snapshot, (FileBytes(file_size, 0)));
|
||||||
|
|
||||||
|
std::barrier start(5);
|
||||||
|
std::array<std::exception_ptr, 5> errors;
|
||||||
|
std::vector<FileView> snapshots;
|
||||||
|
std::vector<FileBytes> expected_snapshots;
|
||||||
|
std::vector<std::jthread> participants;
|
||||||
|
for (std::size_t producer = 0; producer < 4; ++producer) {
|
||||||
|
participants.emplace_back([&, producer] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
try {
|
||||||
|
for (std::size_t index = producer; index < chunks.size(); index += 4) {
|
||||||
|
collector.OnNewChunk(21, chunks[index].pos, FileBytes(chunks[index].bytes));
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
errors[producer] = std::current_exception();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
participants.emplace_back([&] {
|
||||||
|
start.arrive_and_wait();
|
||||||
|
try {
|
||||||
|
for (int i = 0; i < 32; ++i) {
|
||||||
|
auto view = collector.GetFile(21, false);
|
||||||
|
expected_snapshots.push_back(*view);
|
||||||
|
snapshots.push_back(std::move(view));
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
errors[4] = std::current_exception();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
participants.clear();
|
||||||
|
for (const auto& error : errors) {
|
||||||
|
if (error) {
|
||||||
|
std::rethrow_exception(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
EXPECT_EQ(*collector.GetFile(21), original);
|
||||||
|
EXPECT_EQ(*initial_snapshot, (FileBytes(file_size, 0)));
|
||||||
|
for (std::size_t index = 0; index < snapshots.size(); ++index) {
|
||||||
|
EXPECT_EQ(*snapshots[index], expected_snapshots[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
27
tests/test_data.hpp
Normal file
27
tests/test_data.hpp
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include "file_collector/file_collector.hpp"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <random>
|
||||||
|
|
||||||
|
namespace test_data {
|
||||||
|
|
||||||
|
using namespace file_collector;
|
||||||
|
|
||||||
|
inline FileBytes Pattern(std::size_t size, std::uint32_t seed = 0xC0FFEE) {
|
||||||
|
std::mt19937 rng(seed);
|
||||||
|
FileBytes bytes(size);
|
||||||
|
std::generate(bytes.begin(), bytes.end(), [&] { return static_cast<std::uint8_t>(rng()); });
|
||||||
|
return bytes;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline FileBytes Slice(const FileBytes& data, std::size_t pos, std::size_t length) {
|
||||||
|
return FileBytes(data.begin() + static_cast<std::ptrdiff_t>(pos),
|
||||||
|
data.begin() + static_cast<std::ptrdiff_t>(pos + length));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace test_data
|
||||||
|
|
||||||
42
tests/thread_pool_tests.cpp
Normal file
42
tests/thread_pool_tests.cpp
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
#include "thread_pool.hpp"
|
||||||
|
#include <gtest/gtest.h>
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <future>
|
||||||
|
#include <memory>
|
||||||
|
#include <thread>
|
||||||
|
|
||||||
|
using file_collector::detail::ThreadPool;
|
||||||
|
|
||||||
|
TEST(ThreadPool, ZeroReportedWorkersFallsBackToOne) {
|
||||||
|
ThreadPool pool(0);
|
||||||
|
EXPECT_EQ(pool.WorkerCount(), std::size_t{1});
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ThreadPool, ExplicitWorkerCountAndQueueDrain) {
|
||||||
|
std::atomic_int calls{0};
|
||||||
|
{
|
||||||
|
ThreadPool pool(3);
|
||||||
|
EXPECT_EQ(pool.WorkerCount(), std::size_t{3});
|
||||||
|
for (int i = 0; i < 100; ++i) {
|
||||||
|
pool.Submit([&] { calls.fetch_add(1); });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EXPECT_EQ(calls.load(), 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ThreadPool, WorkersSurviveTaskException) {
|
||||||
|
ThreadPool pool(2);
|
||||||
|
std::promise<void> done;
|
||||||
|
auto result = done.get_future();
|
||||||
|
pool.Submit([] { throw std::runtime_error("test exception"); });
|
||||||
|
pool.Submit([&] { done.set_value(); });
|
||||||
|
EXPECT_EQ(result.wait_for(std::chrono::seconds(5)), std::future_status::ready);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(ThreadPool, DefaultUsesHardwareConcurrencyOrOne) {
|
||||||
|
ThreadPool pool;
|
||||||
|
const auto available = std::thread::hardware_concurrency();
|
||||||
|
EXPECT_EQ(pool.WorkerCount(), available == 0 ? 1u : available);
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue