// GC limits: rp_augment_limit and gc_time_limit
// Textbook section: Volume III, chapter 16, "GC", §16.6 "rp_augment_limit/gc_time_limit".
// What it demonstrates: setting and reading the GC options — rp_augment_limit and
//   gc_time_limit — via extra_runtime_option; the effect on working with long
//   values (fragmentation/growth).
// Build: g++ -std=c++17 -I<libmdbx-include> -I../common 22-gc-limits.c++ -lmdbx
// Run: ./22-gc-limits
// Expected output (numbers depend on the system):
//   rp_augment_limit = <N>
//   gc_time_limit = <M>
//   ok: GC limits set and read
// On failure — message to stderr and exit 1.
//
// SPDX-License-Identifier: Apache-2.0

#include <cstdint>
#include <iostream>
#include <string>

#include "common.h++"
#include <mdbx.h++>

int main() {
  try {
    const std::string path = std::string(example::tmpdir()) + "/mdbx-22-gc-limits.mdbx";
    mdbx::env::remove(path);

    // A workload with long values takes tens of MB, so the upper bound is
    // set explicitly instead of relying on the system default size (which may
    // be insufficient on 32-bit platforms).
    mdbx::env::geometry geo;
    geo.make_dynamic(1 * mdbx::env::geometry::MiB, 64 * mdbx::env::geometry::MiB);
    mdbx::env_managed env = example::env_open(path, geo);

    using opt = mdbx::env::extra_runtime_option;

    // GC limits: 0 for gc_time_limit means "allocate the entire available
    // transaction time budget"; rp_augment_limit limits the growth of the page
    // reserve for a reclaim operation.
    env.set_extra_option(opt::rp_augment_limit, 128 * 1024);
    // gc_time_limit is specified in 1/65536 fractions of a second (16.16 fixed point):
    // 2500 ≈ 38 ms for searching page runs in the GC inside a transaction.
    env.set_extra_option(opt::gc_time_limit, 2500);

    // A workload with long values: forces the GC to work harder.
    {
      auto txn = env.start_write();
      auto table = txn.open_map(nullptr);
      for (int i = 0; i < 2000; ++i) {
        const auto key = "k" + std::to_string(i);
        const std::string value(4096 + (i % 7) * 512, 'v');
        txn.insert(table, mdbx::slice(key), mdbx::slice(value));
      }
      txn.commit();
      auto del = env.start_write();
      auto dtable = del.open_map(nullptr);
      for (int i = 0; i < 2000; i += 2)
        del.erase(dtable, mdbx::slice("k" + std::to_string(i)));
      del.commit();
    }

    std::cout << "rp_augment_limit = " << env.extra_option(opt::rp_augment_limit) << "\n";
    std::cout << "gc_time_limit = " << env.extra_option(opt::gc_time_limit) << "\n";

    std::cout << "ok: GC limits set and read\n";
    return EXIT_SUCCESS;
  } catch (const std::exception &ex) {
    std::cerr << "error: " << ex.what() << "\n";
    return EXIT_FAILURE;
  }
}