From 1d3260c935798fefa136d9467046e066805f2a08 Mon Sep 17 00:00:00 2001 From: blevouschurverantunt <35274597+blevouschurverantunt@users.noreply.github.com> Date: Mon, 30 Nov 2026 08:49:15 -0600 Subject: [PATCH] Add opt-in store_orders sync stream New sync option `store_orders` (default false) and event type `store_order`: one record per store order in the two refining store categories, with the bundle, what was paid and what each chest granted. The game delivers the result of a purchase in two forms, and both are read: a single order (platform entity group OrderVirtualGood, one Order) and a list of orders (OrdersVirtualGood, an Orders message), which is how a bulk purchase arrives. Every order of a list goes through the same rules as a single order; an order that fails them is skipped on its own and the others are still sent. The records of one response are published together. The Order and Orders messages are added to the generated protobuf roots. Event: bid, at (Order.created, epoch seconds), category, tier, paid [{rid, amount}] and chests [[{id, kind, qty}]], every key always present. The order carries the bundle id but not the price, so the event is resolved against the last store bundle snapshot of the session: the category is the one listing the bundle (refining_materials or refining_ship_parts only), the tier is the one cost entry whose quantity equals the number of order items, and paid is that entry's resources. Each order item gives one chest from its first customized content set. An order is only sent when it has an id, a creation time and items, all items share one non-zero bundle id, the bundle is listed in a refining category, exactly one price matches the item count and it has resources; the reason for a skip is logged at debug level without any id. A payload that cannot be parsed sends nothing. The order id only keys the record; it is not part of the event or of any log line. An order is not sent again while it is among the 300 most recent orders kept, whether it arrived alone or in a list: orders are a journal (delivered one per request, acknowledged per record, and never removed by a later response), so an order pruned from it would be sent again if the game repeated its response. The platform response is read when any of store_offers, store_bundles or store_orders is enabled, store bundles are processed when either of the last two is, and each target receives only the streams it enables. Docs: a record carries no order id, so a retried record is identical and bid and at together recognise it; only the 300 most recent orders are kept per session, undelivered ones are dropped when a new session starts, and an order is only recorded when the store bundles were received in the same session. Tests: single orders and their skip rules; a list of three orders of different bundles and tiers; a list of 60 orders; the same order as a single result and inside a list; a list mixing refining, unknown, non-refining, mixed-bundle and incomplete orders; empty and unparseable lists; the option off; and the wire types of Orders (repeated field 1) and OrderItem.bundleId and bundleVersion (fixed32). Co-Authored-By: Claude Fable 5.2 --- docs/FEATURES.md | 1 + .../example_community_patch_settings_en.toml | 4 + src/mod/config.h | 2 + src/mod/sync/records.cc | 92 +++++++ src/mod/sync/state.cc | 11 + src/mod/sync/sync.cc | 50 ++-- src/mod/sync/sync.h | 17 +- tests/sync_logic.cc | 235 +++++++++++++++++- zig/deps/protobuf_roots.txt | 2 + 9 files changed, 394 insertions(+), 20 deletions(-) diff --git a/docs/FEATURES.md b/docs/FEATURES.md index 52a383147..bec5d3e28 100644 --- a/docs/FEATURES.md +++ b/docs/FEATURES.md @@ -104,6 +104,7 @@ Each target has its own options and access token. | Fleets | Live fleet state: each state change with cargo, mining and timers, and the server's view of deployed fleets. Every change is sent, not just the latest; up to 300 per session. Off unless a target sets `fleets`. | | Store | Faction store offers: favor level prices, requirements and remaining purchases. Off unless a target sets `store_offers`. | | Store bundles | Sync store bundles for the refining and alliance tournament store categories: costs, requirements, contents, remaining purchases and validity times. Off unless a target sets `store_bundles`. | +| Store orders | Sync the results of refining store purchases (`refining_materials` and `refining_ship_parts`), one record per order, including each order of a bulk purchase: the bundle, what was paid and what each chest granted. Up to 300 recent orders per session; orders not yet delivered when a new session starts are dropped. A request that got no answer is retried, so a record can arrive more than once. It carries no order id: a repeat is identical, and `bid` and `at` together recognise it. An order is only recorded when the store's bundles were received in the same session. Off unless a target sets `store_orders`. | | Profile | Your own level, XP, Power and Haven unlock. Other players' records are never sent. Off unless a target sets `profile`. | | Mission requirements | Acceptance requirements of the mission specs the client receives (login, active missions, and systems you enter). Off unless a target sets `mission_requirements`. | diff --git a/docs/configuration/example_community_patch_settings_en.toml b/docs/configuration/example_community_patch_settings_en.toml index 5c06c4185..7b1fac42d 100644 --- a/docs/configuration/example_community_patch_settings_en.toml +++ b/docs/configuration/example_community_patch_settings_en.toml @@ -1013,6 +1013,10 @@ store_bundles = false # Sync faction store offer data. Requires mod 1.1.10 or newer. store_offers = false +# Sync the results of refining store purchases, one record per order, bulk purchases included (the bundle, what was paid and what each chest granted). +# Only orders of bundles received in the same session are recorded. A retried record can arrive twice; bid and at recognise it. +store_orders = false + # Do you want to sync owned forbidden tech data? tech = true diff --git a/src/mod/config.h b/src/mod/config.h index 500dcf85c..ed5ddcf3b 100644 --- a/src/mod/config.h +++ b/src/mod/config.h @@ -46,6 +46,7 @@ struct SyncConfig { bool slots = false; bool store_bundles = false; bool store_offers = false; + bool store_orders = false; bool tech = false; bool traits = false; @@ -72,6 +73,7 @@ constexpr auto SyncOptions = std::to_array({ {"slots", &SyncConfig::slots}, {"store_bundles", &SyncConfig::store_bundles}, {"store_offers", &SyncConfig::store_offers}, + {"store_orders", &SyncConfig::store_orders}, {"tech", &SyncConfig::tech}, {"traits", &SyncConfig::traits}, }); diff --git a/src/mod/sync/records.cc b/src/mod/sync/records.cc index 6a1f33ccf..5a7755018 100644 --- a/src/mod/sync/records.cc +++ b/src/mod/sync/records.cc @@ -967,6 +967,98 @@ void ProcessStoreBundles(const Input& input) Publish(Stream::kStoreBundles, std::move(records), input.generation); } +// A refining store purchase: the platform's result of an order, resolved against the last store bundle snapshot. +// The order says which bundle it bought but not what it cost, so the paid price is the cost entry whose quantity is +// the number of items granted. Anything that cannot be resolved exactly is not sent. The order id only keys the +// record, so a repeated response is skipped for as long as the order is among the kRecentStoreOrders most recent kept; +// an older one has been pruned and would be sent again. It is never part of the event or of a log line. +// Adds the record to `records` when the order resolves; an order that does not is skipped on its own. +void AddStoreOrder(const content::Order& order, uint64_t generation, RecordSet& records) +{ + const auto skip = [](std::string_view reason) { logging::Debug("process", "store order", "not sent: {}", reason); }; + if (order.orderid().empty() || !order.has_created() || order.created().seconds() <= 0 || order.orderitems().empty()) + return skip("the order is incomplete"); + if (LoadRecord(Stream::kStoreOrders, order.orderid(), generation)) + return; + const uint32_t bundle_id = order.orderitems(0).bundleid(); + if (bundle_id == 0 || !std::ranges::all_of(order.orderitems(), [bundle_id](const content::OrderItem& item) { + return item.bundleid() == bundle_id; + })) + return skip("the items do not share one bundle"); + + json bundle; + std::string category; + for (const auto name : kBundleCategories) { + const auto snapshot = LoadRecord(Stream::kStoreBundles, std::string(name), generation); + if (!snapshot) + continue; + const auto found = std::ranges::find_if(snapshot->at("bundles"), [bundle_id](const json& candidate) { + return candidate.at("bid").get() == bundle_id; + }); + if (found != snapshot->at("bundles").end()) { + bundle = *found; + category = std::string(name); + break; + } + } + if (category.empty()) + return skip("no store snapshot lists the bundle"); + if (category != "refining_materials" && category != "refining_ship_parts") + return skip("the bundle is not in a refining category"); + + const auto count = static_cast(order.orderitems_size()); + const json* tier = nullptr; + size_t index = 0; + size_t match = 0; + size_t at = 0; + for (const auto& cost : bundle.at("cost")) { + if (cost.at("qty").get() == count) { + tier = &cost; + index = at; + ++match; + } + ++at; + } + if (match != 1) + return skip(match ? "several prices match the item count" : "no price matches the item count"); + if (tier->at("res").empty()) + return skip("the matching price has no resources"); + + auto chests = json::array(); + for (const auto& item : order.orderitems()) { + const auto& customized = item.content().customized(); + chests.push_back(customized.empty() ? json::array() : BundleItems(customized.Get(0).contents())); + } + records[order.orderid()] = {{"bid", bundle_id}, {"at", order.created().seconds()}, {"category", category}, + {"tier", index}, {"paid", tier->at("res")}, {"chests", std::move(chests)}}; +} + +// One order, delivered alone as the platform's order result. +void ProcessStoreOrder(const Input& input) +{ + const auto parsed = Parse(input, "store order"); + if (!parsed) + return; + RecordSet records; + AddStoreOrder(*parsed, input.generation, records); + if (!records.empty()) + Publish(Stream::kStoreOrders, std::move(records), input.generation); +} + +// A list of orders, which the game delivers for a bulk purchase: every order goes through the same rules as a single +// one, an order that fails them is skipped on its own, and the records of one response are published together. +void ProcessStoreOrders(const Input& input) +{ + const auto parsed = Parse(input, "store orders"); + if (!parsed) + return; + RecordSet records; + for (const auto& order : parsed->orders_()) + AddStoreOrder(order, input.generation, records); + if (!records.empty()) + Publish(Stream::kStoreOrders, std::move(records), input.generation); +} + // UserProfiles responses also list other players; only the local player's record is read. The level is the in-memory // Level captured with the response: it lags one own-record response after a level-up. (The record's own level is a // fixed32 field; it read 0 while it was declared as a varint.) diff --git a/src/mod/sync/state.cc b/src/mod/sync/state.cc index 623fc758b..22f3ef3dd 100644 --- a/src/mod/sync/state.cc +++ b/src/mod/sync/state.cc @@ -59,6 +59,8 @@ namespace Spec{Stream::kSlots, &SyncConfig::slots, "slot"}, Spec{Stream::kStoreBundles, &SyncConfig::store_bundles, "store_bundle"}, Spec{Stream::kStoreOffers, &SyncConfig::store_offers, "store_offer"}, + Spec{Stream::kStoreOrders, &SyncConfig::store_orders, "store_order", FullSync::kNever, nullptr, nullptr, + kRecentStoreOrders}, Spec{Stream::kTech, &SyncConfig::tech, "ft"}, Spec{Stream::kTraits, &SyncConfig::traits, "trait"}, }; @@ -126,6 +128,15 @@ bool RecordStore::Contains(Stream stream, const json& key) const return records && records->records.contains(key); } +std::shared_ptr RecordStore::Find(Stream stream, const json& key) const +{ + const auto& records = streams_[static_cast(stream)]; + if (!records) + return nullptr; + const auto found = records->records.find(key); + return found == records->records.end() ? nullptr : found->second; +} + bool RecordStore::Apply(Stream stream, RecordSet records, Update mode) { auto& slot = streams_[static_cast(stream)]; diff --git a/src/mod/sync/sync.cc b/src/mod/sync/sync.cc index 535f6c72d..78d1681f2 100644 --- a/src/mod/sync/sync.cc +++ b/src/mod/sync/sync.cc @@ -87,26 +87,37 @@ namespace } // Platform responses (store offers among them) pass through the same registry code as game server responses. Only - // store offers are read from them, and only while a target wants the stream that reads them: unlike the categories - // above, a target that turns them on waits for the next store refresh. Each processor runs only for its own - // option, and a target receives only the streams it enables. + // the store groups are read from them, and only while a target wants a stream that reads them: unlike the + // categories above, a target that turns them on waits for the next store refresh. Each processor runs only for its + // own options, and a target receives only the streams it enables. Store bundles are also kept while only the + // order stream is on, because orders are resolved against the last snapshot. void HandlePlatformResponse(PlatformServiceResponse* response) { const auto config = Config::Sync::Get(); const auto& options = config->options; for (auto* entity_group : il2cpp::Items(response->EntityGroups())) { - auto* group = entity_group && entity_group->Type() == PlatformEntityGroup::Kind::StoreOffers - ? entity_group->Group() - : nullptr; + if (!entity_group) + continue; + const auto kind = entity_group->Type(); + const bool order_kind = + kind == PlatformEntityGroup::Kind::OrderVirtualGood || kind == PlatformEntityGroup::Kind::OrdersVirtualGood; + auto* group = kind == PlatformEntityGroup::Kind::StoreOffers || order_kind ? entity_group->Group() : nullptr; if (!group) continue; const auto bytes = group->Span(); + const auto push = [&](Processor process) { + pending_jobs.Push({process, {.generation = SessionGeneration(), .bytes = {bytes.begin(), bytes.end()}}}); + }; + if (order_kind) { + // One order, or the list of orders a bulk purchase arrives as. + if (options.store_orders) + push(kind == PlatformEntityGroup::Kind::OrderVirtualGood ? ProcessStoreOrder : ProcessStoreOrders); + continue; + } if (options.store_offers) - pending_jobs.Push( - {ProcessStoreOffers, {.generation = SessionGeneration(), .bytes = {bytes.begin(), bytes.end()}}}); - if (options.store_bundles) - pending_jobs.Push( - {ProcessStoreBundles, {.generation = SessionGeneration(), .bytes = {bytes.begin(), bytes.end()}}}); + push(ProcessStoreOffers); + if (options.store_bundles || options.store_orders) + push(ProcessStoreBundles); } } @@ -132,10 +143,12 @@ namespace if (service_response && service_response->Is()) { for (auto* group : il2cpp::Items(service_response->EntityGroups())) HandleEntityGroup(group); - } else if (service_response - && (Config::Sync::Get()->options.store_offers || Config::Sync::Get()->options.store_bundles)) { - if (auto* platform = service_response->As()) - HandlePlatformResponse(platform); + } else if (service_response) { + const auto config = Config::Sync::Get(); + const auto& options = config->options; + if (options.store_offers || options.store_bundles || options.store_orders) + if (auto* platform = service_response->As()) + HandlePlatformResponse(platform); } return original(_this, parsing_context, service_response, method); } @@ -369,6 +382,13 @@ void FlushBattleAcks() } } +std::shared_ptr LoadRecord(Stream stream, const json& key, uint64_t generation) +{ + auto& state = State(); + std::scoped_lock lock(state.mutex); + return generation == state.records.Generation() ? state.records.Find(stream, key) : nullptr; +} + // Starts, reconfigures and retires target threads to match [sync] after a settings reload. Runs every frame, so // it returns at once while the settings object is unchanged. Game thread only. void FollowSettings() diff --git a/src/mod/sync/sync.h b/src/mod/sync/sync.h index 126f22dd9..a9efc8e71 100644 --- a/src/mod/sync/sync.h +++ b/src/mod/sync/sync.h @@ -224,6 +224,7 @@ enum class Stream { kSlots, kStoreBundles, kStoreOffers, + kStoreOrders, kTech, kTraits, kCount @@ -241,6 +242,8 @@ using Snapshot = std::map, RecordKeyLess>; inline constexpr size_t kRecentBattles = 300; // Fleet changes are a journal too, bounded like battles. inline constexpr size_t kRecentFleetChanges = 300; +// Purchase results are a journal as well: each is delivered once, and only the recent ones are kept. +inline constexpr size_t kRecentStoreOrders = 300; // The battle journals one target has acknowledged, kept across sessions so a login does not send it, or fetch from // the game server, what it already holds. Most recent last. The fingerprint identifies the endpoint they were @@ -302,10 +305,12 @@ enum class Update { kMerge, kFull, kReplace }; class RecordStore { public: - void Reset(); - bool Apply(Stream stream, RecordSet records, Update mode = Update::kMerge); - bool Contains(Stream stream, const json& key) const; - uint64_t Generation() const + void Reset(); + bool Apply(Stream stream, RecordSet records, Update mode = Update::kMerge); + bool Contains(Stream stream, const json& key) const; + // The current record under `key`, or null. + std::shared_ptr Find(Stream stream, const json& key) const; + uint64_t Generation() const { return generation_; } private: @@ -443,12 +448,16 @@ Processor ProcessorFor(EntityGroup::Kind kind); void ProcessRealtimeSlot(const Input& input); void ProcessStoreOffers(const Input& input); void ProcessStoreBundles(const Input& input); +void ProcessStoreOrder(const Input& input); +void ProcessStoreOrders(const Input& input); // The local player's own record from a UserProfiles response; needs user_id and level. void ProcessOwnProfile(const Input& input); // sync.cc. Publish drops records from an older session. void Publish(Stream stream, RecordSet records, uint64_t generation, Update mode = Update::kMerge); bool HasBattle(uint64_t id, uint64_t generation); +// The record a stream holds under `key` in this session, or null. Processors read earlier responses through it. +std::shared_ptr LoadRecord(Stream stream, const json& key, uint64_t generation); // Battle journals acknowledged across sessions. True when at least one target syncs battle logs and every such // target has acknowledged `id`. Any thread. bool BattleAckedEverywhere(uint64_t id); diff --git a/tests/sync_logic.cc b/tests/sync_logic.cc index 1b9e33a36..b62bb4e71 100644 --- a/tests/sync_logic.cc +++ b/tests/sync_logic.cc @@ -1164,6 +1164,13 @@ void WireTypes() // Resource.amountUlong (6) is fixed64. const auto resource = ParseWire(std::string("\x31\x00\x94\x35\x77\x00\x00\x00\x00", 9)); Check(resource.amountulong() == 2000000000u, "resource amountUlong is fixed64"); + // OrderItem: bundleId (1) and bundleVersion (2) are fixed32. + // Orders: field 1 repeated, length-delimited. + const auto orders = ParseWire(std::string("\x0a\x03\x0a\x01x\x0a\x05\x0a\x01y\x12\x00", 12)); + Check(orders.orders__size() == 2 && orders.orders_(0).orderid() == "x" && orders.orders_(1).orderid() == "y", + "an order list holds repeated orders at field 1"); + const auto item = ParseWire(std::string("\x0d\x1e\x00\x00\x00\x15\x02\x00\x00\x00", 10)); + Check(item.bundleid() == 30 && item.bundleversion() == 2, "order item bundle id and version are fixed32"); const auto profile = ParseWire(std::string("\x1d\x28\x00\x00\x00\x25\x27\x00\x00\x00", 10)); Check(profile.level() == 40 && profile.levellastawarded() == 39, "profile levels are fixed32"); } @@ -1197,7 +1204,8 @@ std::map Drain(Delivery& target) { std::map uploads; while (auto upload = target.Next(store, now)) { - uploads[upload->Type()] = upload->Records(); + for (auto& record : upload->Records()) + uploads[upload->Type()].push_back(std::move(record)); target.Complete(std::move(*upload), true, store.Generation(), now); } return uploads; @@ -1319,6 +1327,227 @@ void StoreBundles() const auto got = Drain(other); Check(got.size() == 1 && got.contains("store_offer"), "store_bundles is honoured per target"); } +std::string OrderBytes(const std::string& id, const std::vector& bundles, int64_t created = 1700000100) +{ + content::Order order; + order.set_orderid(id); + order.mutable_created()->set_seconds(created); + int64_t chest = 0; + for (const auto bundle : bundles) { + auto* item = order.add_orderitems(); + item->set_bundleid(bundle); + auto* contents = item->mutable_content()->add_customized()->mutable_contents(); + AddItem(contents, "21", "resource", 100 + chest); + AddItem(contents, "22", "resource", 5); + ++chest; + } + return order.SerializeAsString(); +} +content::Bundles OrderSnapshot() +{ + content::Bundles response = StoreResponse(); + // Bundle 31 has two prices of the same quantity. + auto* same = AddBundle(response, 31, "refining_ship_parts"); + for (uint32_t quantity : {2u, 2u, 3u}) { + auto* cost = same->add_cost(); + cost->set_quantity(quantity); + cost->add_cost_()->set_id("7"); + } + // Bundles 32 and 33 have their own prices. + for (const auto& [id, category, rid] : + {std::tuple{32u, "refining_ship_parts", "4000000001"}, std::tuple{33u, "refining_materials", "4000000002"}}) { + auto* other = AddBundle(response, id, category); + for (uint32_t quantity : {1u, 2u, 5u}) { + auto* cost = other->add_cost(); + cost->set_quantity(quantity); + auto* resource = cost->add_cost_(); + resource->set_id(rid); + resource->set_amount(quantity * 100); + } + } + return response; +} +void StoreOrders() +{ + auto target = Target(); + const auto order = [](const std::string& bytes) { ProcessStoreOrder({store.Generation(), bytes}); }; + // Before any snapshot: nothing can be resolved. + order(OrderBytes("order-a", {30, 30})); + Check(Drain(target).empty(), "an order without a snapshot sends nothing"); + + ProcessStoreBundles({store.Generation(), OrderSnapshot().SerializeAsString()}); + Drain(target); + order(OrderBytes("order-a", {30, 30})); + const auto sent = Drain(target); + Check(sent.size() == 1 && sent.at("store_order").size() == 1, "a refine order is sent"); + const json expected = json::parse(R"({"type":"store_order","bid":30,"at":1700000100,"category":"refining_materials", + "tier":1,"paid":[{"rid":4000000000,"amount":2000}], + "chests":[[{"id":21,"kind":"resource","qty":100},{"id":22,"kind":"resource","qty":5}], + [{"id":21,"kind":"resource","qty":101},{"id":22,"kind":"resource","qty":5}]]})"); + Check(sent.at("store_order")[0] == expected, "tier and paid come from the quantity match"); + Check(sent.at("store_order")[0].dump().find("order-a") == std::string::npos, "the order id is not in the event"); + + // The same order again, even after the snapshot it resolves from changed, is not sent a second time: with the + // quantities swapped it would resolve to another tier and price. + order(OrderBytes("order-a", {30, 30})); + auto changed = OrderSnapshot(); + changed.mutable_bundles_(0)->mutable_cost(0)->set_quantity(2); + changed.mutable_bundles_(0)->mutable_cost(1)->set_quantity(1); + ProcessStoreBundles({store.Generation(), changed.SerializeAsString()}); + order(OrderBytes("order-a", {30, 30})); + Check(Drain(target).count("store_order") == 0, "a repeated order is not sent again"); + ProcessStoreBundles({store.Generation(), OrderSnapshot().SerializeAsString()}); + Drain(target); + + order(OrderBytes("order-b", {30, 30, 30, 30})); + Check(!Drain(target).contains("store_order"), "an item count matching no price sends nothing"); + order(OrderBytes("order-c", {31, 31})); + Check(!Drain(target).contains("store_order"), "two prices with the same quantity send nothing"); + order(OrderBytes("order-d", {8})); + Check(!Drain(target).contains("store_order"), "an alliance games bundle sends nothing"); + order(OrderBytes("order-e", {77, 77})); + Check(!Drain(target).contains("store_order"), "an unknown bundle sends nothing"); + order(OrderBytes("order-f", {30, 10})); + order(OrderBytes("order-g", {0, 0})); + order(OrderBytes("order-h", {})); + order(OrderBytes("order-i", {30}, 0)); + order(OrderBytes("", {30})); + Check(!Drain(target).contains("store_order"), "mixed, zero, empty or incomplete orders send nothing"); + + // One item and no customized content: an empty chest list. + content::Order bare; + bare.set_orderid("order-j"); + bare.mutable_created()->set_seconds(1700000200); + bare.add_orderitems()->set_bundleid(30); + order(bare.SerializeAsString()); + const auto single = Drain(target); + Check(single.contains("store_order") && single.at("store_order")[0].at("tier") == 0 + && single.at("store_order")[0].at("chests") == json::parse("[[]]"), + "an item without customized content is an empty chest"); + + // An order list handed to the single-order processor does not parse as an Order: the list's field 1 is read as the + // string orderId, and the wrapped order holds a creation time whose varint bytes are not valid UTF-8. Nothing is + // sent. + const auto wrapped = Field('\x0a', OrderBytes("order-k", {30})); + content::Order misread; + Check(!misread.ParseFromString(wrapped), "a wrapped order does not parse as an order"); + order(wrapped); + Check(!Drain(target).contains("store_order"), "an order list read as a single order sends nothing"); + + // Only the most recent orders are remembered: an order pruned from the journal is delivered again if repeated. + for (size_t i = 0; i <= kRecentStoreOrders; ++i) { + order(OrderBytes("prune-" + std::to_string(i), {30, 30})); + Check(Drain(target).contains("store_order"), "every new order is sent"); + } + order(OrderBytes("prune-" + std::to_string(kRecentStoreOrders), {30, 30})); + Check(!Drain(target).contains("store_order"), "a remembered order is not sent again"); + order(OrderBytes("prune-0", {30, 30})); + Check(Drain(target).contains("store_order"), "an order pruned from the journal can be sent again"); + + // A target with only store_orders gets orders but not the snapshot; the bundles stay available to the processor. + store.Reset(); + auto only_orders = SyncTargetConfig{Options()}; + only_orders.store_bundles = false; + only_orders.store_offers = false; + Delivery other; + other.Configure(only_orders); + ProcessStoreBundles({store.Generation(), OrderSnapshot().SerializeAsString()}); + order(OrderBytes("order-l", {30, 30, 30})); + const auto got = Drain(other); + Check(got.size() == 1 && got.contains("store_order") && got.at("store_order")[0].at("tier") == 2, + "a target with only store_orders receives no store bundles"); +} +std::string OrderListBytes(const std::vector& orders) +{ + content::Orders list; + for (const auto& order : orders) + list.add_orders_()->ParseFromString(order); + return list.SerializeAsString(); +} +void StoreOrderLists() +{ + auto target = Target(); + const auto list = [](const std::vector& orders) { + ProcessStoreOrders({store.Generation(), OrderListBytes(orders)}); + }; + const auto single = [](const std::string& bytes) { ProcessStoreOrder({store.Generation(), bytes}); }; + ProcessStoreBundles({store.Generation(), OrderSnapshot().SerializeAsString()}); + Drain(target); + + // A bulk purchase: three orders of three bundles in one response. + const std::vector bulk{OrderBytes("list-a", {30, 30}), OrderBytes("list-b", {32}), + OrderBytes("list-c", {33, 33, 33, 33, 33})}; + list(bulk); + const auto sent = Drain(target); + Check(sent.size() == 1 && sent.at("store_order").size() == 3, "every order of a list is sent"); + std::map by_bundle; + for (const auto& record : sent.at("store_order")) { + by_bundle[record.at("bid").get()] = record; + Check(record.at("at") == 1700000100, "an order keeps its own time"); + Check(record.dump().find("list-") == std::string::npos, "no order id is in a record"); + } + Check(by_bundle.size() == 3 && by_bundle.at(30).at("tier") == 1 && by_bundle.at(32).at("tier") == 0 + && by_bundle.at(33).at("tier") == 2, + "each order resolves its own tier"); + Check(by_bundle.at(30).at("paid") == json::parse(R"([{"rid":4000000000,"amount":2000}])") + && by_bundle.at(32).at("paid") == json::parse(R"([{"rid":4000000001,"amount":100}])") + && by_bundle.at(33).at("paid") == json::parse(R"([{"rid":4000000002,"amount":500}])"), + "each order has its own price"); + Check(by_bundle.at(30).at("chests").size() == 2 && by_bundle.at(32).at("chests").size() == 1 + && by_bundle.at(33).at("chests").size() == 5, + "each order has a chest per item"); + Check(by_bundle.at(30).at("category") == "refining_materials" + && by_bundle.at(32).at("category") == "refining_ship_parts", + "each order has its own category"); + list(bulk); + Check(!Drain(target).contains("store_order"), "the same list again sends nothing"); + + // The same order as a single result and then inside a list is sent once; the list sends only the new one. + single(OrderBytes("list-d", {30})); + Check(Drain(target).at("store_order").size() == 1, "a single order is sent"); + list({OrderBytes("list-d", {30}), OrderBytes("list-e", {30})}); + Check(Drain(target).at("store_order").size() == 1, "an order already sent is not sent again from a list"); + list({OrderBytes("list-e", {30})}); + single(OrderBytes("list-e", {30})); + Check(!Drain(target).contains("store_order"), "and not the other way round either"); + + // One order that fails a rule does not stop the others. + list({OrderBytes("list-f", {77, 77}), OrderBytes("list-g", {8}), OrderBytes("list-h", {30, 10}), + OrderBytes("list-i", {32}), OrderBytes("list-j", {30}, 0), OrderBytes("list-k", {0}), + OrderBytes("list-l", {33, 33, 33, 33})}); + const auto mixed = Drain(target); + Check(mixed.size() == 1 && mixed.at("store_order").size() == 1 && mixed.at("store_order")[0].at("bid") == 32, + "only the refining order of a mixed list is sent"); + + // Nothing to read. + list({}); + ProcessStoreOrders({store.Generation(), std::string("\xff\xff\x01garbage")}); + ProcessStoreOrders({store.Generation(), std::string()}); + Check(!Drain(target).contains("store_order"), "an empty or unparseable list sends nothing"); + + // An order that repeats inside one list is sent once. + list({OrderBytes("list-m", {32}), OrderBytes("list-m", {32})}); + Check(Drain(target).at("store_order").size() == 1, "an order repeated inside a list is sent once"); + + // A large bulk purchase: every order is kept, and the same list again sends nothing. + std::vector large; + const uint32_t bundles[] = {30, 32, 33}; + for (size_t i = 0; i < 60; ++i) + large.push_back(OrderBytes("large-" + std::to_string(i), std::vector(1 + i % 2, bundles[i % 3]))); + list(large); + const auto many = Drain(target); + Check(many.size() == 1 && many.at("store_order").size() == 60, "all 60 orders of a large list are sent"); + list(large); + Check(!Drain(target).contains("store_order"), "a large list again sends nothing"); + + // The target without store_orders gets nothing from the lists it is handed. + auto off = SyncTargetConfig{Options()}; + off.store_orders = false; + Delivery other; + other.Configure(off); + list({OrderBytes("list-n", {30})}); + Check(!Drain(other).contains("store_order"), "a target without store_orders receives no orders"); +} void ProtobufJournals() { const auto body = BattleReportBody(SyntheticJournal()); @@ -1400,6 +1629,8 @@ void Publish(Stream stream, RecordSet records, uint64_t generation, Update mode) if (generation == store.Generation()) store.Apply(stream, std::move(records), mode); } +std::shared_ptr LoadRecord(Stream stream, const json& key, uint64_t generation) +{ return generation == store.Generation() ? store.Find(stream, key) : nullptr; } void QueueNewBattles(const std::vector&, uint64_t) {} void CachePlayerNames(const Input&) {} void CacheAllianceNames(const Input&) {} @@ -1463,6 +1694,8 @@ int main() run("wire types", WireTypes); run("store offer counts", StoreOfferCounts); run("store bundles", StoreBundles); + run("store orders", StoreOrders); + run("store order lists", StoreOrderLists); if (!failures) std::cout << "Sync wire and delivery tests passed\n"; return failures ? 1 : 0; diff --git a/zig/deps/protobuf_roots.txt b/zig/deps/protobuf_roots.txt index e43e467c6..4b3af20ac 100644 --- a/zig/deps/protobuf_roots.txt +++ b/zig/deps/protobuf_roots.txt @@ -1,5 +1,7 @@ # Sync entry points. Field message types and nested messages are included transitively. Digit.PrimePlatform.Content.Bundles +Digit.PrimePlatform.Content.Order +Digit.PrimePlatform.Content.Orders Digit.PrimeServer.Models.ActiveMissionsResponse Digit.PrimeServer.Models.AllianceGamePropertiesResponse Digit.PrimeServer.Models.AllianceGetBankResourcesResponse