diff --git a/CMakeLists.txt b/CMakeLists.txt index 4776ecf..1965d96 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -109,6 +109,7 @@ if(GTest_FOUND) tests/unit/PutIfAbsentTest.cpp tests/unit/ReplaceTest.cpp tests/unit/ContainsKeyTest.cpp + tests/unit/BulkOpsTest.cpp tests/unit/HashAwareRoutingTest.cpp tests/unit/ErrorHandlingTest.cpp tests/unit/ServerSelectionTest.cpp @@ -193,6 +194,11 @@ if(GTest_FOUND) tests/integration/ErrorHandlingIntegrationTest.cpp ) + # Bulk operations (PUT_ALL / GET_ALL) end-to-end (single server) + add_executable(bulkops_integration_tests + tests/integration/BulkOpsIntegrationTest.cpp + ) + # Hot Rod URI end-to-end (single server) — fromUri parse->connect->op chain add_executable(fromuri_integration_tests tests/integration/FromUriIntegrationTest.cpp @@ -285,6 +291,13 @@ if(GTest_FOUND) # Note: NOT gtest_main - we provide our own main() ) + target_link_libraries(bulkops_integration_tests + PRIVATE + hotrod-client + GTest::gtest + # Note: NOT gtest_main - we provide our own main() + ) + target_link_libraries(topology_integration_tests PRIVATE hotrod-client @@ -425,6 +438,7 @@ if(GTest_FOUND) add_test(NAME ReplaceIntegrationTests COMMAND replace_integration_tests) add_test(NAME ContainsKeyIntegrationTests COMMAND containskey_integration_tests) add_test(NAME ErrorHandlingIntegrationTests COMMAND errorhandling_integration_tests) + add_test(NAME BulkOpsIntegrationTests COMMAND bulkops_integration_tests) add_test(NAME FromUriIntegrationTests COMMAND fromuri_integration_tests) add_test(NAME TopologyIntegrationTests COMMAND topology_integration_tests) add_test(NAME ConcurrentClientsTests COMMAND concurrent_clients_tests) @@ -479,6 +493,10 @@ if(GTest_FOUND) WORKING_DIRECTORY ${CMAKE_BINARY_DIR} LABELS "integration;docker" ) + set_tests_properties(BulkOpsIntegrationTests PROPERTIES + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + LABELS "integration;docker" + ) set_tests_properties(ErrorHandlingIntegrationTests PROPERTIES WORKING_DIRECTORY ${CMAKE_BINARY_DIR} LABELS "integration;docker" @@ -538,7 +556,8 @@ if(GTest_FOUND) PingIntegrationTests GetIntegrationTests GetWithMetadataIntegrationTests PutIntegrationTests RemoveIntegrationTests RemoveWithVersionIntegrationTests ReplaceWithVersionIntegrationTests PutIfAbsentIntegrationTests ReplaceIntegrationTests - ContainsKeyIntegrationTests ErrorHandlingIntegrationTests FromUriIntegrationTests + ContainsKeyIntegrationTests ErrorHandlingIntegrationTests BulkOpsIntegrationTests + FromUriIntegrationTests TopologyIntegrationTests ConcurrentClientsTests HashAwareRoutingIntegrationTests ConcurrentMultiServerTests RetryViewIntegrationTests PingRetryIntegrationTests MultiSeedIntegrationTests diff --git a/README.md b/README.md index 073a42c..2c4639a 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,8 @@ operation as a `std::future`. - **Metadata and version-based (CAS) operations** — `getWithMetadata`, `putIfAbsent`, `replace`, `containsKey`, `removeWithVersion`, `replaceWithVersion`. +- **Bulk operations** — `putAll` / `getAll` store and fetch many entries in one + request. - **Async API** — every operation returns a `std::future`; operations on a server share one multiplexed connection. - **Hash-aware routing and failover** — consistent hashing (MurmurHash3 x64_32), @@ -147,6 +149,10 @@ if (auto entry = cache.getWithMetadata(key).get()) { int64_t version = entry->metadata.version; bool replaced = cache.replaceWithVersion(key, newValue, version).get(); } + +// Bulk: store/fetch many entries in one request +cache.putAll({{k1, v1}, {k2, v2}}).get(); // std::map +auto found = cache.getAll({k1, k2}).get(); // map of the keys that exist ``` Pass `previousValue = true` to `put`/`putIfAbsent`/`replace`/`remove` to receive diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index bba33b9..950d2c5 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1536,3 +1536,125 @@ parent directory, so running `coverage-diff` standalone (without first running `coverage`, which does the mkdir) crashed with `FileNotFoundError: .../coverage/ patch.html`. Each coverage target must be independently runnable; the earlier smoke tests masked this by always running `coverage` first. + +## 2026-12-03 — Step 12 part 1: PUT_ALL + GET_ALL shipped; BULK_GET deferred + +**What:** Implemented the two multi-key bulk operations `putAll` (0x2D→0x2E) and +`getAll` (0x2F→0x30) on `RemoteCache`, with `RetryView` forwarders, 10 unit tests +(`tests/unit/BulkOpsTest.cpp`, wire-layout regression vectors) and 5 end-to-end +Docker tests (`tests/integration/BulkOpsIntegrationTest.cpp`). Unit 284→294, +integration 107→112 (23→24 suites). + +**API shape:** `putAll(std::map, lifespan, maxIdle) → +future`; `getAll(std::set) → future>`. +Map/set mirror Java's `Map`/`Set` signatures; `ByteArray` (`std::vector`) +is ordered, so `std::map` keying is free. Missing keys are simply omitted from the +`getAll` result (not an error), matching Java `GetAllOperation`. + +**Wire format (confirmed against Java + hotrod40.ksy, which agree here):** +- PUT_ALL request: `time_units(u1) + [lifespan vLong] + [maxIdle vLong] + + entry_count(vInt) + (key lp_bytes, value lp_bytes)*`. Expiration encoding is the + *same* shared encoder `put()` uses (Java `codec.writeExpirationParams`): lifespan + unit in the HIGH nibble, maxIdle in the LOW nibble. Response: status only (Void). +- GET_ALL request: `key_count(vInt) + (key lp_bytes)*`. Response: + `entry_count(vInt) + (key lp_bytes, value lp_bytes)*`. + +**Routing decision:** bulk ops are dispatched like a *keyless* op via +`selectAnyServer` (same path as `ping`), NOT per-key hash routing. The whole +request goes to one server, which fans out to each key's owners — matching the +single-request structure of Java `GetAllOperation`/`PutAllOperation`. A future +optimization could split by segment and scatter/gather, but Java does not, so we +match it. + +**Why BULK_GET was deferred (gotcha — STATUS.md was wrong):** the backlog listed +`BULK_GET (0x1F)`, but **0x1F is QUERY**; BULK_GET is actually **0x19→0x1A**. The +modern Java client has **no `BulkGetOperation`** (only `GetAll`/`PutAll` and the +streaming `GetAllBulk`/`PutAllBulk` publisher ops), and the `hotrod40.ksy` +`bulk_get_response` is under-specified (its `chunk` carries only a `value`, no +key). Per the AGENTS.md rule (sources disagree → stop), shipping it off that +schema would be guesswork. Deferred until a real use case justifies verifying the +live wire format against a running server. GET_ALL covers the "fetch many known +keys" need that BULK_GET's iterator style was the old answer to. + +## 2026-12-03 — Bulk ops route by owner (scatter/gather), superseding the same-day single-server note + +**Supersedes** the routing paragraph in the earlier 2026-12-03 Step 12 entry, +which claimed putAll/getAll send one request to a single server "matching Java". +**That was wrong** — it was based on reading only the leaf `GetAllOperation` / +`PutAllOperation` and missing the wrapper layer. + +**What Java actually does:** `RemoteCacheImpl.getAllAsync`/`putAll` wrap the keys +in `GetAllBulkOperation` / `PutAllBulkOperation` (subclasses of +`HotRodBulkOperation`). `gatherOperations` resolves each key's **owner** via the +routing function and groups keys into `Map`, issues one +`GetAllOperation`/`PutAllOperation` **per owner concurrently**, and `reduce` +merges the per-owner results. So each node only ever receives the keys it owns. + +**What we now do (correctly):** `RemoteCache::groupKeysByConnection` routes every +key through the existing single-key selector `selectServerForKey` and groups keys +by the returned connection. In `HASH_DISTRIBUTION_AWARE` mode that yields one +group per primary owner (inheriting exclusion / proxy / seed fallback for free); +in BASIC / no-topology mode every key resolves to the bootstrap connection, so the +groups collapse to a single request (the natural fallback — nothing to partition +on without hash topology). `putAll`/`getAll` then scatter one sub-op per group via +`conn->execute` (concurrent on the wire, since execute dispatches immediately and +the multiplexed read loops handle responses) and a deferred future gathers them — +merging the maps for `getAll`, collapsing to void for `putAll`. + +**Partial-failure semantics (follows D2, which diverges from Java):** this is the +one place bulk ops are deliberately NOT Java-equivalent. +- *Before send (automatic failover):* grouping routes each key via + `selectServerForKey`, so a key whose owner is unreachable at grouping time is + redirected to a reachable backup/proxy/seed. A bulk op only throws before sending + if the whole cluster is unreachable. (Same spirit as Java's routing fallback.) +- *After send (user-decided, NOT automatic):* if a sub-op is sent and then fails + (error status or dropped connection), the whole op fails — the first error is + rethrown, enriched with the union of nodes tried across all partitions (so the + failed node is in `e.triedNodes`); no partial map is returned. There is NO + automatic per-partition retry. The caller retries the whole op via `excluding(e)`, + which re-partitions the full key set minus `e.triedNodes` (coarser than Java's + per-sub-op retry, but safe — getAll is read-only, putAll re-writes idempotently). + +Java differs: each partition sub-op goes through `executeOnSingleAddress`, which +auto-retries on another server (`RetryingHotRodOperation` + `addFailedServer`) up +to `maxRetries` before the aggregate fails. We intentionally do not — retry stays +user-decided (D2, `docs/ERROR_HANDLING_DESIGN.md:57,128`), exactly as for every +other op in this client. The "whole op fails if any partition fails, no partial +results" aggregate shape itself DOES match Java's `AggregateCompletionStage`. + +**Why reuse selectServerForKey per key instead of a bespoke partitioner:** it +reuses the already-tested routing (owner ordering, `orderKeyCandidates`, +exclusion, proxy/seed fallback, connection pooling + lifetime) and automatically +gives the correct BASIC-mode single-group behavior. Cost is one `stateMutex_` +lock + candidate evaluation per key; acceptable for realistic bulk sizes, and +optimizable later if a hot path needs it. + +**Verified:** `HashAwareRoutingIntegrationTest.BulkOpsPartitionAcrossOwners` +(60-key batch, asserts it spans ≥2 owners, then checks every entry round-trips via +putAll→get/getAll) and `BulkGetAllOmitsMissingAcrossOwners`, both against a real +3-node cluster. Integration 112→114 (still 24 suites); unit unchanged at 294. + +## 2026-12-03 — Step 12 bulk-op test coverage completed to convention + +**Context:** there is no numeric coverage gate or tooling in this repo (no gcov/ +lcov/codecov, no CI threshold). The bar is the behavioral convention +(WORKFLOW.md: test vectors → unit tests → implementation, plus integration for +behavior, and an `excluding()` integration test per op as in +`RetryViewIntegrationTest`). A coverage review of the bulk feature found three +new-code paths no test exercised; all three are now closed: + +1. **putAll non-default lifespan/maxIdle** — the expiration-encoding branches in + `putAllImpl` were only covered by a *mirror* of the logic in a unit test, never + the impl. Added `BulkOpsIntegrationTest.PutAllWithExpirationSetsMetadata` + (putAll with lifespan/maxIdle, verified via getWithMetadata). +2. **empty putAll** short-circuit — added `BulkOpsIntegrationTest.PutAllEmptyIsNoOp`. +3. **bulk + excluding() / user-decided retry** — added + `HashAwareRoutingIntegrationTest.BulkOpsExcludingRoutesAroundOwner` (cluster): + putAll/getAll via `excluding({owner})` still round-trips the full batch by + re-routing the excluded owner's partition to a backup/proxy. Exercises + `groupKeysByConnection` honoring `ctx.excludeNodes` and the RetryView forwarders. + +**Still intentionally untested:** after-send partition failure via killing a node +mid-op (needs fault injection). The before-send re-route is covered by (3); the +after-send fail-the-whole-op path is simple and shared with every other op's +error handling. Final counts: unit 294, integration 117 (24 suites). diff --git a/docs/STATUS.md b/docs/STATUS.md index 7f064bf..c5ac2d6 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -33,14 +33,16 @@ _(Full per-session workflow: [`WORKFLOW.md`](WORKFLOW.md).)_ _The 1–3 concrete things to do next. Keep this short and current._ -1. **Step 12 — Bulk operations.** `GET_ALL` (0x2F), `PUT_ALL` (0x2D), - `BULK_GET` (0x1F, iterator-style). See 📋 Backlog below. -2. **Benchmark the multiplexing path** — the async rewrite targets 5–10× +1. **Benchmark the multiplexing path** — the async rewrite targets 5–10× concurrent throughput; never measured. -3. **Small cleanup:** read header "other params" when `paramCount > 0` +2. **Small cleanup:** read header "other params" when `paramCount > 0` (two `TODO`s in `src/operations/RemoteCache.cpp`). +3. **Optional: BULK_GET (0x19)** — deferred (legacy, absent from modern Java, + under-specified in the schema; see 📋 Backlog + [`DECISIONS.md`](DECISIONS.md)). + Only pick this up if a real iterator-style use case appears. _Recently shipped (detail in "Working and shipped" + [`DECISIONS.md`](DECISIONS.md)): +Step 12 bulk ops — `putAll` (0x2D) + `getAll` (0x2F); BULK_GET deferred (2026-12-03); Docs aligned with the Go/Java clients (#26) — Go single-book layout, local render + GitHub Pages, all topic chapters fleshed out, README restructured (2026-12-02); Docker integration coverage for mutual TLS + SASL PLAIN + SASL EXTERNAL @@ -61,10 +63,17 @@ pull from here next. Step numbers follow (STATUS.md) is authoritative for what's done._ **Remaining roadmap steps:** -- [ ] **Step 12 — Bulk operations.** `GET_ALL` (0x2F), `PUT_ALL` (0x2D), - `BULK_GET` (0x1F, iterator-style). +- [x] **Step 12 — Bulk operations.** `PUT_ALL` (0x2D) and `GET_ALL` (0x2F) + shipped (see "Working and shipped"). `BULK_GET` deferred — see below. **Other known work (not roadmap steps):** +- [ ] **BULK_GET (deferred).** Iterator-style bulk fetch. NOTE: this is opcode + **0x19→0x1A**, not 0x1F (0x1F is QUERY — the old backlog note was wrong). It is + absent from the modern Java client and under-specified in `hotrod40.ksy` + (`bulk_get_response.chunk` has no key), so it needs the live wire format verified + against a running server before implementing. `GET_ALL` covers fetching many + known keys; revisit BULK_GET only for a genuine iterate-everything use case. See + [`DECISIONS.md`](DECISIONS.md) (2026-12-03). - [ ] **OAUTHBEARER integration coverage** — the last non-SCRAM SASL mechanism without an end-to-end Docker test. Needs real token infra (a token-realm backed by Keycloak, or a static-JWT public key + a pre-minted token). PLAIN, EXTERNAL, @@ -172,6 +181,16 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ - **replace** (0x07/0x08) — store only if key present; returns `future>` (replaced entry when `previousValue` set) - **containsKey** (0x0F/0x10) — key-existence test; returns `future` +- **Bulk ops (Step 12):** **putAll** (0x2D/0x2E) stores a + `map` (`future`; shared lifespan/maxIdle, same + expiration encoding as `put`); **getAll** (0x2F/0x30) fetches a `set` → + `future>` (absent keys omitted). Keys are **partitioned + by owner** (`groupKeysByConnection`, which routes each key through + `selectServerForKey`): in HASH mode one sub-op per primary owner, scattered + concurrently and merged (client-side scatter/gather, matching Java + `HotRodBulkOperation`); in BASIC/no-topology mode the groups collapse to a single + request. Any sub-op failure fails the whole op (retryable via `excluding(e)`). + Exposed on `RetryView` too. BULK_GET deferred - **Typed error surfacing (Step 11a):** server ERROR responses (opcode 0x50) are parsed (status + length-prefixed message) and thrown as `HotRodClientException` — a pure-data exception carrying `FailurePhase`, @@ -197,30 +216,36 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ that stalls a subprocess fails fast instead of hanging the whole CI job. See [`DECISIONS.md`](DECISIONS.md). -**Test status:** **284 unit** (verified 2026-11-12) + **107 integration** (23 -suites, verified 2026-11-13), all passing. This is the one authoritative count — +**Test status:** **294 unit** (verified 2026-12-03) + **117 integration** (24 +suites, verified 2026-12-03), all passing. This is the one authoritative count — other docs describe *what* is covered rather than repeating totals. Counts read from the built test binaries via `--gtest_list_tests`, so they match what actually -runs. (The +6 integration tests on 2026-11-13 are the mutual-TLS round-trip/URI/ -no-cert-rejected cases — `MutualTlsIntegrationTests` — the SASL EXTERNAL -cert-identity round-trip + URI cases — `ExternalAuthIntegrationTests` — and a PLAIN -case added to `AuthIntegrationTests`.) +runs. (The +10 unit / +10 integration on 2026-12-03 are the Step 12 bulk ops — +`BulkOpsTest` wire-layout vectors for putAll/getAll; `BulkOpsIntegrationTests` (7) +single-server round-trip / missing-key / overwrite / after-disconnect / empty-set / +non-default-expiration / empty-putAll; and three `HashAwareRoutingIntegrationTests` +cases that prove client-side scatter/gather splits a multi-owner batch and that +`excluding()` re-routes bulk partitions around an excluded owner.) - Unit (`./build/unit_tests`, <1s) — wire primitives/headers, consistent hashing, - server-selection/retry helpers, the SASL handshake (SCRAM family + + server-selection/retry helpers, bulk-op wire layout (putAll/getAll, `BulkOpsTest`), + the SASL handshake (SCRAM family + PLAIN/EXTERNAL/OAUTHBEARER, against fake servers), the TLS handshake (server-auth + mutual TLS, in-process OpenSSL server), and the Hot Rod URI parser. - Integration (`ctest`, spins up Docker Infinispan single-server + multi-node - clusters; also green on Linux CI) — CRUD + metadata/CAS, topology & hash-aware - routing, keyed/keyless retry (`RetryView`/ping), SASL against a secured server + clusters; also green on Linux CI) — CRUD + metadata/CAS, bulk ops + (putAll/getAll round-trip `BulkOpsIntegrationTests`, plus owner-partitioning + across a 3-node cluster in `HashAwareRoutingIntegrationTests`), topology & + hash-aware routing, keyed/keyless retry (`RetryView`/ping), SASL against a secured server (SCRAM family + PLAIN via `AuthIntegrationTests`; EXTERNAL over mutual TLS via `ExternalAuthIntegrationTests`), server-authenticated TLS (`TlsIntegrationTests`) and mutual TLS (`MutualTlsIntegrationTests`), Hot Rod URI `fromUri`, and multi-server seed failover. -- Full run: `ctest --test-dir build --output-on-failure` covers **24 suites** - (1 unit + 23 integration). Last full end-to-end run 2026-10-19 (100% pass at the - then-current 21 suites); unit suite re-verified 2026-11-12 (284 pass), and the - `Auth`/`Tls`/`MutualTls`/`ExternalAuth` integration suites verified 2026-11-13 - (7 + 5 + 3 + 2 pass) after the integration-coverage changes. +- Full run: `ctest --test-dir build --output-on-failure` covers **25 suites** + (1 unit + 24 integration). Last full end-to-end run 2026-10-19 (100% pass at the + then-current 21 suites); unit suite re-verified 2026-12-03 (294 pass), the + `BulkOps` integration suite verified 2026-12-03 (7 pass, single server), and the + three new `HashAwareRouting` bulk cases (partition-across-owners, omit-missing, + excluding-re-routes) verified against a real 3-node cluster after Step 12. - **Concurrency validated (2026-09-25):** the concurrent suites pass 8/8 (incl. `ConcurrentWithFailover`), and a ThreadSanitizer run (`build-tsan/`) reports **no races in production code** — slice-4's `stateMutex_`/`shared_ptr` @@ -232,7 +257,7 @@ case added to `AuthIntegrationTests`.) allocated". CI runners have these ports free. **Not started / open:** see [📋 Backlog](#-backlog-the-whole-list) above for the -full list (Steps 10–12, benchmarks, TLS, code TODOs). +full list (BULK_GET deferred, OAUTHBEARER integration, benchmarks, code TODOs). --- diff --git a/documentation/topics/cache-operations.adoc b/documentation/topics/cache-operations.adoc index 8171c83..54e1584 100644 --- a/documentation/topics/cache-operations.adoc +++ b/documentation/topics/cache-operations.adoc @@ -80,6 +80,27 @@ if (auto entry = cache.getWithMetadata(key).get()) { effect, and `false` when the version did not match (the entry was modified) or the key did not exist. +=== Bulk operations + +`putAll` stores many entries, and `getAll` fetches many keys, in a single request. +All `putAll` entries share one `lifespan`/`maxIdle` (the same expiration rules as +`put`). `getAll` returns only the requested keys that exist — keys absent from the +cache are simply omitted from the result map. + +[source,cpp] +---- +cache.putAll({{k1, v1}, {k2, v2}, {k3, v3}}).get(); // std::map + +std::set keys{k1, k2, k3}; +std::map found = cache.getAll(keys).get(); +---- + +With hash-aware routing the client partitions the keys by their owner and sends +one sub-request to each owner concurrently, then merges the results — so each node +handles only the keys it owns. Without topology information (BASIC intelligence) +the keys are sent together to the connected server. If any sub-request fails the +whole operation fails, and can be retried with `excluding()`. + .Operation summary [cols="1,2",options="header"] |=== @@ -88,5 +109,6 @@ key did not exist. | `put`, `putIfAbsent`, `replace`, `remove` | `std::optional` | `getWithMetadata` | `std::optional` | `containsKey`, `removeWithVersion`, `replaceWithVersion` | `bool` -| `ping` | `void` +| `getAll` | `std::map` +| `putAll`, `ping` | `void` |=== diff --git a/include/hotrod/RemoteCache.h b/include/hotrod/RemoteCache.h index 04b3dc0..dda05cb 100644 --- a/include/hotrod/RemoteCache.h +++ b/include/hotrod/RemoteCache.h @@ -12,6 +12,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -291,6 +294,50 @@ class RemoteCache { std::future replaceWithVersion(const ByteArray& key, const ByteArray& value, int64_t version, uint64_t lifespan = 0, uint64_t maxIdle = 0); + /** + * PUT_ALL operation - store multiple key-value pairs in one request (Step 12). + * + * Opcode: 0x2D (PUT_ALL_REQUEST) → 0x2E (PUT_ALL_RESPONSE) + * + * All entries share the same lifespan/maxIdle, exactly like a single put(). + * The whole map is sent as one request to a single server, which distributes + * the entries to their owners; it is therefore not per-key hash-routed (it is + * dispatched like a keyless op). The response carries only a success status. + * + * @param entries Key→value pairs to store + * @param lifespan Entry lifespan in seconds (0 = immortal), applied to all + * @param maxIdle Max idle time in seconds (0 = no max idle), applied to all + * @return Future that completes when all entries are stored + * @throws std::runtime_error on communication errors or a non-success status + * (via future.get()) + * + * Reference: + * - Java: org.infinispan.client.hotrod.impl.operations.PutAllOperation + */ + std::future putAll(const std::map& entries, + uint64_t lifespan = 0, uint64_t maxIdle = 0); + + /** + * GET_ALL operation - retrieve multiple keys in one request (Step 12). + * + * Opcode: 0x2F (GET_ALL_REQUEST) → 0x30 (GET_ALL_RESPONSE) + * + * The key set is sent as one request to a single server, which gathers the + * values from their owners; it is therefore not per-key hash-routed (it is + * dispatched like a keyless op). Keys that are absent from the cache are simply + * missing from the returned map (no error). + * + * @param keys The keys to fetch + * @return Future with a map of the keys that were found → their values; keys + * not present in the cache are omitted + * @throws std::runtime_error on communication errors or a non-success status + * (via future.get()) + * + * Reference: + * - Java: org.infinispan.client.hotrod.impl.operations.GetAllOperation + */ + std::future> getAll(const std::set& keys); + /** * Close connection to server. */ @@ -547,6 +594,13 @@ class RemoteCache { std::future replaceWithVersionImpl(const ByteArray& key, const ByteArray& value, int64_t version, uint64_t lifespan, uint64_t maxIdle, const RetryContext& ctx); + // Multi-key ops: keys are partitioned by owner and one sub-request is sent to + // each owner concurrently, then the results merged — mirroring the Java client's + // HotRodBulkOperation gatherOperations/reduce. See groupKeysByConnection. + std::future putAllImpl(const std::map& entries, + uint64_t lifespan, uint64_t maxIdle, const RetryContext& ctx); + std::future> getAllImpl(const std::set& keys, + const RetryContext& ctx); std::string host_; uint16_t port_; @@ -647,6 +701,27 @@ class RemoteCache { std::shared_ptr selectAnyServer(const RetryContext& ctx = {}, std::vector* triedOut = nullptr); + /** + * Partition keys by the connection that serves them, for the multi-key bulk + * ops (putAll/getAll). Routes each key through selectServerForKey — so in + * HASH_DISTRIBUTION_AWARE mode keys group by primary owner (honoring ctx + * exclusions, proxy and seed fallback), and in BASIC / no-topology mode every + * key resolves to the bootstrap connection, collapsing to a single group. This + * mirrors the Java client's HotRodBulkOperation.gatherOperations (one sub-op + * per owner), reached here by reusing the single-key routing per key. + * + * Each returned group pairs a (live, never-null) connection with the subset of + * @p keys it should carry; groups are in first-seen order. Every node attempted + * is accumulated into *triedOut (for exception enrichment / retry). + * + * Does NOT hold stateMutex_ across the whole call — selectServerForKey locks + * per key internally. Throws HotRodClientException (BeforeSend) if any key has + * no reachable server (nothing has been sent yet at that point). + */ + std::vector, std::vector>> + groupKeysByConnection(const std::vector& keys, const RetryContext& ctx, + std::vector* triedOut); + /** * Get or create connection for a specific server. * diff --git a/include/hotrod/RetryView.h b/include/hotrod/RetryView.h index d20cc01..f6e7f03 100644 --- a/include/hotrod/RetryView.h +++ b/include/hotrod/RetryView.h @@ -7,6 +7,8 @@ #include #include #include +#include +#include namespace hotrod { @@ -83,6 +85,15 @@ class RetryView { return cache_->replaceWithVersionImpl(key, value, version, lifespan, maxIdle, ctx_); } + std::future putAll(const std::map& entries, + uint64_t lifespan = 0, uint64_t maxIdle = 0) { + return cache_->putAllImpl(entries, lifespan, maxIdle, ctx_); + } + + std::future> getAll(const std::set& keys) { + return cache_->getAllImpl(keys, ctx_); + } + private: RemoteCache* cache_; // non-owning; must outlive this view RetryContext ctx_; // bound exclusion set diff --git a/src/operations/RemoteCache.cpp b/src/operations/RemoteCache.cpp index d677ab2..8b59bdb 100644 --- a/src/operations/RemoteCache.cpp +++ b/src/operations/RemoteCache.cpp @@ -975,6 +975,206 @@ namespace hotrod }); } + std::vector, std::vector>> + RemoteCache::groupKeysByConnection(const std::vector &keys, const RetryContext &ctx, + std::vector *triedOut) + { + // Group keys by the connection that serves them. Each key is routed through + // the single-key selector: in HASH_DISTRIBUTION_AWARE mode that is the key's + // primary owner (with the usual exclusion / proxy / seed fallback), so keys + // group by owner exactly like Java HotRodBulkOperation.gatherOperations; in + // BASIC / no-topology mode every key resolves to the bootstrap connection, so + // the groups collapse to one (a single request). Connections are pooled, so + // repeated routing to the same owner returns the same shared_ptr — we dedup on + // the raw pointer. Routing runs before any send, so a BeforeSend throw here is + // safe (nothing has been dispatched yet). + std::vector, std::vector>> groups; + std::map indexByConn; + std::vector tried; + + for (const auto &key : keys) + { + std::vector keyTried; + std::shared_ptr conn = selectServerForKey(key, ctx, &keyTried); + tried = unionNodes(tried, keyTried); + + auto it = indexByConn.find(conn.get()); + if (it == indexByConn.end()) + { + indexByConn.emplace(conn.get(), groups.size()); + groups.push_back({conn, {key}}); + } + else + { + groups[it->second].second.push_back(key); + } + } + + if (triedOut) + *triedOut = tried; + return groups; + } + + std::future RemoteCache::putAll(const std::map &entries, + uint64_t lifespan, uint64_t maxIdle) + { + return putAllImpl(entries, lifespan, maxIdle, RetryContext{}); + } + + std::future RemoteCache::putAllImpl(const std::map &entries, + uint64_t lifespan, uint64_t maxIdle, + const RetryContext &ctx) + { + // Empty map → nothing to send (Java issues no sub-ops either). + if (entries.empty()) + return std::async(std::launch::deferred, [] {}); + + // Expiration byte shared by every sub-request, identical to put(): lifespan + // unit in the HIGH nibble, maxIdle in the LOW nibble; 0x07 = DEFAULT (no + // duration vLong follows). Java PutAllOperation uses the same encoder. + uint8_t timeUnits = 0; + timeUnits |= (lifespan == 0 ? 0x07 : 0x00) << 4; + timeUnits |= (maxIdle == 0 ? 0x07 : 0x00); + + // Each PUT_ALL sub-response carries no body (Void); any non-success status is + // an error, surfaced via resp.error below. + auto bodyParser = [](uint8_t status, Connection * /*conn*/, uint8_t /*protocolVersion*/, int32_t /*flags*/) -> std::any + { + if (status != 0x00) + throw HotRodClientException("PUT_ALL failed with status: " + std::to_string(status), + FailurePhase::ServerError, status); + return {}; + }; + + // Partition keys by owner, then scatter one PUT_ALL per owner. Grouping (and + // thus any routing failure) happens before the first send. + std::vector keyVec; + keyVec.reserve(entries.size()); + for (const auto &kv : entries) + keyVec.push_back(kv.first); + + std::vector tried; + auto groups = groupKeysByConnection(keyVec, ctx, &tried); + + std::vector> conns; + std::vector> responses; + conns.reserve(groups.size()); + responses.reserve(groups.size()); + for (auto &group : groups) + { + ByteArray body; + body.push_back(timeUnits); + if (lifespan > 0) + Codec::writeVLong(body, lifespan); + if (maxIdle > 0) + Codec::writeVLong(body, maxIdle); + Codec::writeVInt(body, static_cast(group.second.size())); + for (const auto &key : group.second) + { + Codec::writeByteArray(body, key); + Codec::writeByteArray(body, entries.at(key)); + } + conns.push_back(group.first); + responses.push_back(group.first->execute(body, 0x2D, 0x2E, bodyParser, cacheName_)); + } + + // Gather: wait on every sub-op and fail the whole op if any failed (matching + // Java's aggregate). conns is captured to keep the connections alive. + return std::async(std::launch::deferred, + [conns = std::move(conns), responses = std::move(responses), + tried = std::move(tried), excluded = ctx.excludeNodes]() mutable + { + std::exception_ptr firstError; + for (auto &rf : responses) + { + Response resp = rf.get(); + if (resp.error && !firstError) + firstError = resp.error; + } + if (firstError) + rethrowWithTriedNodes(firstError, tried, excluded); + }); + } + + std::future> RemoteCache::getAll(const std::set &keys) + { + return getAllImpl(keys, RetryContext{}); + } + + std::future> RemoteCache::getAllImpl(const std::set &keys, + const RetryContext &ctx) + { + if (keys.empty()) + return std::async(std::launch::deferred, [] { return std::map{}; }); + + // Each GET_ALL sub-response body is: entry_count (vInt) + (key lp_bytes, + // value lp_bytes)*. Keys absent from the cache are simply omitted (not an + // error). The whole body is consumed so the shared read loop stays aligned. + auto bodyParser = [](uint8_t status, Connection *conn, uint8_t /*protocolVersion*/, int32_t /*flags*/) -> std::any + { + if (status != 0x00) + throw HotRodClientException("GET_ALL failed with status: " + std::to_string(status), + FailurePhase::ServerError, status); + std::map part; + VInt count = conn->receiveVInt(); + for (VInt i = 0; i < count; ++i) + { + ByteArray k = conn->receiveByteArray(); + ByteArray v = conn->receiveByteArray(); + part.emplace(std::move(k), std::move(v)); + } + return part; + }; + + // Partition keys by owner, then scatter one GET_ALL per owner and merge the + // per-owner result maps (the partitions are disjoint, so no key collisions). + std::vector keyVec(keys.begin(), keys.end()); + std::vector tried; + auto groups = groupKeysByConnection(keyVec, ctx, &tried); + + std::vector> conns; + std::vector> responses; + conns.reserve(groups.size()); + responses.reserve(groups.size()); + for (auto &group : groups) + { + ByteArray body; + Codec::writeVInt(body, static_cast(group.second.size())); + for (const auto &key : group.second) + Codec::writeByteArray(body, key); + conns.push_back(group.first); + responses.push_back(group.first->execute(body, 0x2F, 0x30, bodyParser, cacheName_)); + } + + return std::async(std::launch::deferred, + [conns = std::move(conns), responses = std::move(responses), + tried = std::move(tried), excluded = ctx.excludeNodes]() mutable + -> std::map + { + std::map result; + std::exception_ptr firstError; + for (auto &rf : responses) + { + Response resp = rf.get(); + if (resp.error) + { + if (!firstError) + firstError = resp.error; + continue; + } + if (resp.body.has_value()) + { + auto part = std::any_cast>(resp.body); + for (auto &kv : part) + result.emplace(kv.first, kv.second); + } + } + if (firstError) + rethrowWithTriedNodes(firstError, tried, excluded); + return result; + }); + } + RetryView RemoteCache::excluding(std::vector excludeNodes) { return RetryView(*this, RetryContext{std::move(excludeNodes)}); diff --git a/tests/integration/BulkOpsIntegrationTest.cpp b/tests/integration/BulkOpsIntegrationTest.cpp new file mode 100644 index 0000000..12d2c24 --- /dev/null +++ b/tests/integration/BulkOpsIntegrationTest.cpp @@ -0,0 +1,175 @@ +#include +#include +#include +#include +#include "hotrod/RemoteCache.h" +#include "InfinispanTestEnvironment.h" + +using namespace hotrod; +using namespace hotrod::test; + +/** + * PUT_ALL / GET_ALL Integration Tests - No Auth (Step 12, bulk operations) + * + * Reference: + * - ROADMAP Step 12: bulk operations + * - Java: org.infinispan.client.hotrod.impl.operations.PutAllOperation + * - Java: org.infinispan.client.hotrod.impl.operations.GetAllOperation + */ + +namespace { + +void createCacheViaCLI(const std::string& cacheName) { + std::string cmd = "docker exec " + InfinispanTestEnvironment::containerID + + " bash -c \"echo 'create cache --template=org.infinispan.DIST_SYNC " + cacheName + + "' | /opt/infinispan/bin/cli.sh -c http://admin:password@localhost:11222 -f -\" >/dev/null 2>&1"; + std::ignore = system(cmd.c_str()); +} + +ByteArray b(const std::string& s) { return ByteArray(s.begin(), s.end()); } + +} // anonymous namespace + +// putAll stores every entry; getAll reads them back in one request. +TEST(BulkOpsIntegrationTest, PutAllThenGetAllRoundTrip) { + createCacheViaCLI("testcache"); + + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + + std::map entries{ + {b("ba_k1"), b("ba_v1")}, + {b("ba_k2"), b("ba_v2")}, + {b("ba_k3"), b("ba_v3")}, + }; + cache.putAll(entries).get(); + + // Single-key reads see every entry. + EXPECT_EQ(b("ba_v1"), *cache.get(b("ba_k1")).get()); + EXPECT_EQ(b("ba_v2"), *cache.get(b("ba_k2")).get()); + EXPECT_EQ(b("ba_v3"), *cache.get(b("ba_k3")).get()); + + // getAll returns all requested keys that exist. + std::set keys{b("ba_k1"), b("ba_k2"), b("ba_k3")}; + std::map got = cache.getAll(keys).get(); + ASSERT_EQ(3u, got.size()); + EXPECT_EQ(b("ba_v1"), got[b("ba_k1")]); + EXPECT_EQ(b("ba_v2"), got[b("ba_k2")]); + EXPECT_EQ(b("ba_v3"), got[b("ba_k3")]); + + cache.disconnect(); +} + +// getAll omits keys that are not present (no error, just absent from the map). +TEST(BulkOpsIntegrationTest, GetAllOmitsMissingKeys) { + createCacheViaCLI("testcache"); + + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + + cache.put(b("ba_present"), b("here")).get(); + cache.remove(b("ba_missing")).get(); // ensure absent + + std::set keys{b("ba_present"), b("ba_missing")}; + std::map got = cache.getAll(keys).get(); + + ASSERT_EQ(1u, got.size()); + EXPECT_EQ(b("here"), got[b("ba_present")]); + EXPECT_EQ(got.end(), got.find(b("ba_missing"))); + + cache.disconnect(); +} + +// An empty key set returns an empty map without contacting any owner for data. +TEST(BulkOpsIntegrationTest, GetAllEmptyKeySet) { + createCacheViaCLI("testcache"); + + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + + std::map got = cache.getAll(std::set{}).get(); + EXPECT_TRUE(got.empty()); + + cache.disconnect(); +} + +// putAll overwrites existing values for keys already present. +TEST(BulkOpsIntegrationTest, PutAllOverwrites) { + createCacheViaCLI("testcache"); + + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + + cache.put(b("ba_ow"), b("old")).get(); + cache.putAll({{b("ba_ow"), b("new")}}).get(); + + EXPECT_EQ(b("new"), *cache.get(b("ba_ow")).get()); + + cache.disconnect(); +} + +// Bulk ops after disconnect should throw (no silent reconnect), like other ops. +TEST(BulkOpsIntegrationTest, BulkOpsAfterDisconnectThrow) { + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + cache.disconnect(); + + EXPECT_THROW({ cache.putAll({{b("k"), b("v")}}); }, std::runtime_error); + EXPECT_THROW({ cache.getAll(std::set{b("k")}); }, std::runtime_error); +} + +// putAll applies the shared lifespan/maxIdle to every entry — exercises the +// expiration-encoding branches in putAllImpl that the default-expiration tests +// skip. Verified through getWithMetadata (same assertions as the single-key path). +TEST(BulkOpsIntegrationTest, PutAllWithExpirationSetsMetadata) { + createCacheViaCLI("testcache"); + + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + + cache.putAll({{b("ba_exp1"), b("v1")}, {b("ba_exp2"), b("v2")}}, + /*lifespan*/ 3600, /*maxIdle*/ 600).get(); + + for (const auto& k : {b("ba_exp1"), b("ba_exp2")}) { + auto entry = cache.getWithMetadata(k).get(); + ASSERT_TRUE(entry.has_value()); + ASSERT_TRUE(entry->metadata.lifespan.has_value()); + EXPECT_EQ(3600u, entry->metadata.lifespan.value()); + ASSERT_TRUE(entry->metadata.maxIdle.has_value()); + EXPECT_EQ(600u, entry->metadata.maxIdle.value()); + } + + cache.disconnect(); +} + +// An empty putAll is a no-op that completes without error (and without a request). +TEST(BulkOpsIntegrationTest, PutAllEmptyIsNoOp) { + createCacheViaCLI("testcache"); + + RemoteCache cache(InfinispanTestEnvironment::host, + InfinispanTestEnvironment::port, + "testcache"); + cache.connect(); + + EXPECT_NO_THROW(cache.putAll(std::map{}).get()); + + cache.disconnect(); +} + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(new InfinispanTestEnvironment()); + return RUN_ALL_TESTS(); +} diff --git a/tests/integration/HashAwareRoutingIntegrationTest.cpp b/tests/integration/HashAwareRoutingIntegrationTest.cpp index cf43a82..7002923 100644 --- a/tests/integration/HashAwareRoutingIntegrationTest.cpp +++ b/tests/integration/HashAwareRoutingIntegrationTest.cpp @@ -517,6 +517,128 @@ TEST_F(HashAwareRoutingIntegrationTest, TopologyRebalanceUpdatesRouting) << "Keys should be distributed across multiple servers after rebalance"; } +// Bulk ops must partition keys by owner (client-side scatter/gather, like the +// Java HotRodBulkOperation) and still return every entry. With a 3-node cluster +// and HASH routing, a 60-key batch spans all owners; groupKeysByConnection splits +// it into one PUT_ALL/GET_ALL per owner, and the merged result must be complete. +TEST_F(HashAwareRoutingIntegrationTest, BulkOpsPartitionAcrossOwners) +{ + fprintf(stderr, "\n=== Test: BulkOpsPartitionAcrossOwners ===\n"); + + auto cache = createDefaultClient(); + ASSERT_NE(nullptr, cache); + clearAllServers(); + + // Warm up topology so the bulk partition step is hash-aware. + cache->put(ByteArray{'w', 'a', 'r', 'm'}, ByteArray{'u', 'p'}).get(); + ASSERT_TRUE(cache->getConsistentHash().hasHashTopology()); + + const int NUM = 60; + std::map entries; + std::set keys; + std::set ownersSeen; + for (int i = 0; i < NUM; i++) + { + std::string ks = "bulk-" + std::to_string(i); + std::string vs = "val-" + std::to_string(i); + ByteArray k(ks.begin(), ks.end()); + ByteArray v(vs.begin(), vs.end()); + entries.emplace(k, v); + keys.insert(k); + const ServerInfo *owner = cache->getConsistentHash().getPrimaryOwner(k, cache->getTopology()); + if (owner) + ownersSeen.insert(owner->host); + } + // Sanity: the batch really spans multiple owners, so partitioning is exercised + // (otherwise this would silently degrade to the single-group path). + ASSERT_GE(ownersSeen.size(), 2u) + << "Test batch should span multiple owners to exercise partitioning"; + fprintf(stderr, "[TEST] %d keys span %zu owners\n", NUM, ownersSeen.size()); + + // putAll partitions by owner and scatters; every entry must be stored. + cache->putAll(entries).get(); + + // Single-key reads confirm each entry landed (regardless of owner). + for (const auto &kv : entries) + ASSERT_EQ(kv.second, *cache->get(kv.first).get()); + + // getAll partitions by owner, scatters, and merges — must return all NUM keys. + std::map got = cache->getAll(keys).get(); + ASSERT_EQ(static_cast(NUM), got.size()); + for (const auto &kv : entries) + EXPECT_EQ(kv.second, got[kv.first]); +} + +// getAll across owners omits keys that do not exist while keeping those that do. +TEST_F(HashAwareRoutingIntegrationTest, BulkGetAllOmitsMissingAcrossOwners) +{ + fprintf(stderr, "\n=== Test: BulkGetAllOmitsMissingAcrossOwners ===\n"); + + auto cache = createDefaultClient(); + ASSERT_NE(nullptr, cache); + clearAllServers(); + + cache->put(ByteArray{'w', 'a', 'r', 'm'}, ByteArray{'u', 'p'}).get(); + ASSERT_TRUE(cache->getConsistentHash().hasHashTopology()); + + std::map entries; // only the even-numbered keys are stored + std::set keys; // requested set = present + missing + for (int i = 0; i < 40; i++) + { + std::string ks = "mix-" + std::to_string(i); + ByteArray k(ks.begin(), ks.end()); + keys.insert(k); + if (i % 2 == 0) + entries.emplace(k, ByteArray{'v'}); + } + cache->putAll(entries).get(); + + std::map got = cache->getAll(keys).get(); + EXPECT_EQ(entries.size(), got.size()); + for (const auto &kv : entries) + EXPECT_NE(got.end(), got.find(kv.first)); +} + +// Bulk ops honor excluding(): keys whose owner is excluded are routed around it +// (backup owner / proxy), so the whole batch still round-trips. Exercises +// groupKeysByConnection with a non-empty exclusion set and the RetryView +// putAll/getAll forwarders — the user-decided retry path for bulk ops. +TEST_F(HashAwareRoutingIntegrationTest, BulkOpsExcludingRoutesAroundOwner) +{ + fprintf(stderr, "\n=== Test: BulkOpsExcludingRoutesAroundOwner ===\n"); + + auto cache = createDefaultClient(); + ASSERT_NE(nullptr, cache); + clearAllServers(); + + cache->put(ByteArray{'w', 'a', 'r', 'm'}, ByteArray{'u', 'p'}).get(); + ASSERT_TRUE(cache->getConsistentHash().hasHashTopology()); + + std::map entries; + std::set keys; + for (int i = 0; i < 40; i++) + { + std::string ks = "excl-" + std::to_string(i); + ByteArray k(ks.begin(), ks.end()); + entries.emplace(k, ByteArray(ks.begin(), ks.end())); + keys.insert(k); + } + + // Exclude one owner (the primary owner of the first key). Keys it would have + // served must re-route to a backup/proxy; the batch still completes in full. + const ServerInfo *owner = cache->getConsistentHash().getPrimaryOwner(*keys.begin(), cache->getTopology()); + ASSERT_NE(nullptr, owner); + std::vector excluded{{owner->host, owner->port}}; + fprintf(stderr, "[TEST] excluding owner %s:%u\n", owner->host.c_str(), owner->port); + + cache->excluding(excluded).putAll(entries).get(); + std::map got = cache->excluding(excluded).getAll(keys).get(); + + ASSERT_EQ(entries.size(), got.size()); + for (const auto &kv : entries) + EXPECT_EQ(kv.second, got[kv.first]); +} + // Main function - registers the multi-server global environment int main(int argc, char **argv) { diff --git a/tests/unit/BulkOpsTest.cpp b/tests/unit/BulkOpsTest.cpp new file mode 100644 index 0000000..94ddfce --- /dev/null +++ b/tests/unit/BulkOpsTest.cpp @@ -0,0 +1,228 @@ +#include +#include "hotrod/Codec.h" +#include "hotrod/HeaderCodec.h" +#include +#include +#include + +using namespace hotrod; + +/** + * Bulk operation unit tests: PUT_ALL and GET_ALL (Step 12). + * + * These exercise the wire encoding/decoding at the Codec level — the same + * building blocks the RemoteCache::putAllImpl / getAllImpl bodies use — so they + * act as regression vectors for the byte layout independent of a live server. + * + * PUT_ALL request (opcode 0x2D): + * time_units (u1) + [lifespan vLong] + [maxIdle vLong] + * + entry_count (vInt) + (key lp_bytes, value lp_bytes)* + * PUT_ALL response (opcode 0x2E): status only, no body. + * + * GET_ALL request (opcode 0x2F): + * key_count (vInt) + (key lp_bytes)* + * GET_ALL response (opcode 0x30): + * entry_count (vInt) + (key lp_bytes, value lp_bytes)* + * + * Reference: + * - Java: org.infinispan.client.hotrod.impl.operations.PutAllOperation + * - Java: org.infinispan.client.hotrod.impl.operations.GetAllOperation + * - Kaitai: hotrod40.ksy put_all_request / get_all_request / get_all_response + */ + +namespace { + +ByteArray str(const std::string& s) { return ByteArray(s.begin(), s.end()); } + +// Encode a PUT_ALL request body exactly as RemoteCache::putAllImpl does. +ByteArray encodePutAllBody(const std::map& entries, + uint64_t lifespan, uint64_t maxIdle) { + ByteArray body; + uint8_t timeUnits = 0; + timeUnits |= (lifespan == 0 ? 0x07 : 0x00) << 4; // high nibble: lifespan + timeUnits |= (maxIdle == 0 ? 0x07 : 0x00); // low nibble: maxIdle + body.push_back(timeUnits); + if (lifespan > 0) Codec::writeVLong(body, lifespan); + if (maxIdle > 0) Codec::writeVLong(body, maxIdle); + Codec::writeVInt(body, static_cast(entries.size())); + for (const auto& kv : entries) { + Codec::writeByteArray(body, kv.first); + Codec::writeByteArray(body, kv.second); + } + return body; +} + +} // namespace + +// --- PUT_ALL encoding --------------------------------------------------------- + +// time_units when both lifespan and maxIdle are default (0) => 0x77, then the +// entry count and each (key, value) pair as lp_bytes. +TEST(BulkOpsTest, EncodePutAllDefaultExpiration) { + std::map entries{ + {str("k1"), str("v1")}, + {str("k2"), str("v2")}, + }; + + ByteArray body = encodePutAllBody(entries, 0, 0); + + size_t offset = 0; + EXPECT_EQ(0x77, body[offset++]); // both nibbles DEFAULT, no durations follow + + VInt count = Codec::readVInt(body, offset); + EXPECT_EQ(2u, count); + + // std::map iterates in sorted key order: k1 then k2. + EXPECT_EQ(str("k1"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("v1"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("k2"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("v2"), Codec::readByteArray(body, offset)); + EXPECT_EQ(body.size(), offset); // body fully consumed +} + +// With a non-default lifespan the high nibble is SECONDS (0) and a vLong follows; +// maxIdle stays DEFAULT so its low nibble is 0x07 and no second vLong appears. +TEST(BulkOpsTest, EncodePutAllWithLifespan) { + std::map entries{{str("k"), str("v")}}; + + ByteArray body = encodePutAllBody(entries, 60, 0); + + size_t offset = 0; + EXPECT_EQ(0x07, body[offset++]); // lifespan=SECONDS(0)<<4 | maxIdle=DEFAULT(7) + EXPECT_EQ(60u, Codec::readVLong(body, offset)); // lifespan duration + EXPECT_EQ(1u, Codec::readVInt(body, offset)); // entry_count + EXPECT_EQ(str("k"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("v"), Codec::readByteArray(body, offset)); + EXPECT_EQ(body.size(), offset); +} + +// Both lifespan and maxIdle set: high nibble lifespan, low nibble maxIdle, both +// durations present in order (lifespan then maxIdle), matching put(). +TEST(BulkOpsTest, EncodePutAllWithLifespanAndMaxIdle) { + std::map entries{{str("k"), str("v")}}; + + ByteArray body = encodePutAllBody(entries, 120, 30); + + size_t offset = 0; + EXPECT_EQ(0x00, body[offset++]); // both SECONDS + EXPECT_EQ(120u, Codec::readVLong(body, offset)); // lifespan + EXPECT_EQ(30u, Codec::readVLong(body, offset)); // maxIdle + EXPECT_EQ(1u, Codec::readVInt(body, offset)); + EXPECT_EQ(str("k"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("v"), Codec::readByteArray(body, offset)); + EXPECT_EQ(body.size(), offset); +} + +// An empty map still emits a well-formed body: time_units + count 0, no pairs. +TEST(BulkOpsTest, EncodePutAllEmptyMap) { + ByteArray body = encodePutAllBody({}, 0, 0); + size_t offset = 0; + EXPECT_EQ(0x77, body[offset++]); + EXPECT_EQ(0u, Codec::readVInt(body, offset)); + EXPECT_EQ(body.size(), offset); +} + +// --- GET_ALL request encoding ------------------------------------------------- + +// key_count (vInt) followed by each key as lp_bytes, in sorted set order. +TEST(BulkOpsTest, EncodeGetAllRequest) { + std::set keys{str("alpha"), str("beta"), str("gamma")}; + + ByteArray body; + Codec::writeVInt(body, static_cast(keys.size())); + for (const auto& k : keys) Codec::writeByteArray(body, k); + + size_t offset = 0; + EXPECT_EQ(3u, Codec::readVInt(body, offset)); + EXPECT_EQ(str("alpha"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("beta"), Codec::readByteArray(body, offset)); + EXPECT_EQ(str("gamma"), Codec::readByteArray(body, offset)); + EXPECT_EQ(body.size(), offset); +} + +TEST(BulkOpsTest, EncodeGetAllRequestEmpty) { + std::set keys; + ByteArray body; + Codec::writeVInt(body, static_cast(keys.size())); + size_t offset = 0; + EXPECT_EQ(0u, Codec::readVInt(body, offset)); + EXPECT_EQ(body.size(), offset); +} + +// --- GET_ALL response parsing ------------------------------------------------- + +// Parse an entry_count + (key, value)* body into a map, as getAllImpl's parser +// does. Keys absent from the cache are simply not present in the response. +TEST(BulkOpsTest, ParseGetAllResponse) { + // Build a response body: 2 entries. + ByteArray body; + Codec::writeVInt(body, 2); + Codec::writeByteArray(body, str("k1")); + Codec::writeByteArray(body, str("v1")); + Codec::writeByteArray(body, str("k2")); + Codec::writeByteArray(body, str("v2")); + + size_t offset = 0; + std::map result; + VInt count = Codec::readVInt(body, offset); + for (VInt i = 0; i < count; ++i) { + ByteArray key = Codec::readByteArray(body, offset); + ByteArray value = Codec::readByteArray(body, offset); + result.emplace(std::move(key), std::move(value)); + } + + EXPECT_EQ(body.size(), offset); + ASSERT_EQ(2u, result.size()); + EXPECT_EQ(str("v1"), result[str("k1")]); + EXPECT_EQ(str("v2"), result[str("k2")]); +} + +// An empty result (none of the requested keys existed) parses to an empty map. +TEST(BulkOpsTest, ParseGetAllResponseEmpty) { + ByteArray body; + Codec::writeVInt(body, 0); + + size_t offset = 0; + std::map result; + VInt count = Codec::readVInt(body, offset); + for (VInt i = 0; i < count; ++i) { + ByteArray key = Codec::readByteArray(body, offset); + ByteArray value = Codec::readByteArray(body, offset); + result.emplace(std::move(key), std::move(value)); + } + + EXPECT_EQ(body.size(), offset); + EXPECT_TRUE(result.empty()); +} + +// An empty value is a valid entry (length-0 lp_bytes), distinct from a missing key. +TEST(BulkOpsTest, ParseGetAllResponseEmptyValue) { + ByteArray body; + Codec::writeVInt(body, 1); + Codec::writeByteArray(body, str("k")); + Codec::writeByteArray(body, ByteArray{}); // empty value + + size_t offset = 0; + std::map result; + VInt count = Codec::readVInt(body, offset); + for (VInt i = 0; i < count; ++i) { + ByteArray key = Codec::readByteArray(body, offset); + ByteArray value = Codec::readByteArray(body, offset); + result.emplace(std::move(key), std::move(value)); + } + + EXPECT_EQ(body.size(), offset); + ASSERT_EQ(1u, result.size()); + EXPECT_TRUE(result[str("k")].empty()); +} + +// --- Opcode constants --------------------------------------------------------- + +TEST(BulkOpsTest, OpcodeConstants) { + // Per hotrod40.ksy / Java HotRodConstants. Note: BULK_GET is 0x19/0x1A, NOT + // 0x1F (0x1F is QUERY) — see DECISIONS.md; BULK_GET is deferred. + EXPECT_EQ(0x2D, 0x2D); // PUT_ALL_REQUEST + EXPECT_EQ(0x2E, 0x2E); // PUT_ALL_RESPONSE + EXPECT_EQ(0x2F, 0x2F); // GET_ALL_REQUEST + EXPECT_EQ(0x30, 0x30); // GET_ALL_RESPONSE +}