web_service_runtime.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. #include "web_service_runtime.h"
  2. #include <algorithm>
  3. #include <array>
  4. #include <atomic>
  5. #include <chrono>
  6. #include <cstdio>
  7. #include "../../core/logging/log.h"
  8. #include "../../middleware/encoding/bit_reader.h"
  9. #include "../../middleware/web_service/messages/opcode1801.h"
  10. #include "../../middleware/web_service/messages/opcode1821.h"
  11. #include "../../middleware/web_service/messages/opcode1901.h"
  12. #include "../../middleware/web_service/messages/opcode205.h"
  13. #include "../../middleware/web_service/messages/opcode206.h"
  14. #include "../../middleware/web_service/messages/opcode2400.h"
  15. #include "../../middleware/web_service/messages/opcode501_codec.h"
  16. #include "../../middleware/web_service/messages/opcode503.h"
  17. #include "../../middleware/web_service/messages/opcode504.h"
  18. #include "../../middleware/web_service/messages/opcode601/opcode601_codec.h"
  19. #include "../../middleware/web_service/messages/opcode701/opcode701_codec.h"
  20. #include "../../middleware/web_service/messages/opcode702.h"
  21. #include "../../middleware/web_service/messages/opcode801.h"
  22. #include "../../middleware/web_service/messages/opcode901/opcode901_codec.h"
  23. #include "../../middleware/web_service/messages/opcode904/opcode904_codec.h"
  24. #include "../../middleware/web_service/messages/opcode903.h"
  25. #include "../../middleware/web_service/web_service_envelope.h"
  26. #include "../../state/account/account_state.h"
  27. #include "../../state/activity/membership/activity_membership_query.h"
  28. #include "../../state/progression/seasonal_experience.h"
  29. #include "../../state/runtime/runtime.h"
  30. #include "opcode_routes.h"
  31. #include "web_service_actions.h"
  32. namespace sunrise::server::web_service {
  33. /** Web Service opcode used by the Character screen's Equip action. */
  34. constexpr std::uint16_t kEquipOpcode = 403;
  35. /** Web Service opcode used by the Character screen's Unequip action. */
  36. constexpr std::uint16_t kUnequipOpcode = 404;
  37. /** Web Service opcode used by item-state actions such as finisher Favorite. */
  38. constexpr std::uint16_t kItemStateOpcode = 406;
  39. /** Web Service opcode used by the Character screen's Dismantle action. */
  40. constexpr std::uint16_t kItemDismantleOpcode = 402;
  41. /** Web Service opcode used by Collections to create one item instance. */
  42. constexpr std::uint16_t kItemAcquisitionOpcode = 1820;
  43. /**
  44. * Logical status of a refused action. The descriptor biases logical zero to the wire success the
  45. * Client expects, so any other logical value reports a refusal. Its five bits hold no error
  46. * taxonomy, so one code covers every reason and the log line names the actual one.
  47. */
  48. constexpr std::int32_t kRefusedStatus = 1;
  49. constexpr auto kResidentDependentOpcodes =
  50. std::to_array<std::uint16_t>({402, 403, 404, 406, 504, 903, 1801, 1820, 1901, 2400});
  51. /** One refusal line carries both request indices, the clock presence, and the clock verdict. */
  52. constexpr std::size_t kPurchaseLineCapacity = 128;
  53. constexpr std::size_t kEchoLineCapacity = 64;
  54. /**
  55. * Status code answered to a purchase request.
  56. * Any non-zero value refuses. Zero is the success code, so it must not be used here.
  57. */
  58. constexpr std::int32_t kPurchaseRefusedCode = 1;
  59. /** Season of Arrivals artifact vendor row in the installed build's vendor index. */
  60. constexpr std::int16_t kArtifactVendorIndex = 430;
  61. constexpr std::int32_t kArtifactResetGlimmerCost = 20'000;
  62. /**
  63. * Reads the server's own clock for the purchase clock rule.
  64. * The system clock counts from the Unix epoch, which is the same base the request field uses.
  65. * @return Current time in Unix seconds.
  66. */
  67. [[nodiscard]] std::int64_t server_clock_seconds() noexcept {
  68. const auto sinceEpoch = std::chrono::system_clock::now().time_since_epoch();
  69. return std::chrono::duration_cast<std::chrono::seconds>(sinceEpoch).count();
  70. }
  71. /** Issues a strictly increasing family-5 clock, including multiple requests in one second. */
  72. [[nodiscard]] std::uint64_t next_family5_clock() noexcept {
  73. static std::atomic<std::uint64_t> issued{0};
  74. const auto wall = static_cast<std::uint64_t>(server_clock_seconds());
  75. std::uint64_t previous = issued.load(std::memory_order_relaxed);
  76. std::uint64_t next = 0;
  77. do {
  78. next = wall > previous ? wall : previous + 1;
  79. } while (!issued.compare_exchange_weak(previous, next, std::memory_order_relaxed));
  80. return next;
  81. }
  82. /** Records the authoritative world state carried by the client's character write-back. */
  83. void note_character_writeback(const middleware::web_service::Message& message) noexcept {
  84. namespace writeback = middleware::web_service::messages::opcode702;
  85. writeback::Request request{};
  86. const bool parsed = writeback::parse_request(message, request);
  87. std::array<char, core::log::kLineCapacity> line{};
  88. const int written = std::snprintf(line.data(),
  89. line.size(),
  90. "ev=activity stage=writeback result=%s world_state=%u",
  91. parsed ? "ok" : "unparsed",
  92. static_cast<unsigned>(request.worldState));
  93. if (written > 0) {
  94. core::log::write(core::log::Channel::server,
  95. core::log::Level::info,
  96. {line.data(), static_cast<std::size_t>(written)});
  97. }
  98. if (parsed) {
  99. state::activity::membership::note_client_writeback(request.worldState
  100. == writeback::kInWorld);
  101. }
  102. }
  103. /** @return True when a purchase names the seasonal artifact vendor, which is answered here. */
  104. [[nodiscard]] bool names_artifact_vendor(const middleware::web_service::Message& message) noexcept {
  105. namespace purchase_codec = middleware::web_service::messages::opcode901;
  106. purchase_codec::Request purchase{};
  107. return purchase_codec::parse_request(message, purchase)
  108. && purchase.vendorIndex == kArtifactVendorIndex;
  109. }
  110. /**
  111. * Refuses one vendor purchase and answers it.
  112. * No award, cost or stock rule exists yet, so no purchase can succeed. The refusal must still be
  113. * answered, because no answer holds the head of the client's pending queue.
  114. * @param message Parsed purchase request.
  115. * @param response Response-body storage owned by the caller.
  116. * @param written Receives the encoded response size.
  117. * @return True when the refusal was encoded.
  118. */
  119. [[nodiscard]] bool refuse_purchase(const middleware::web_service::Message& message,
  120. std::span<std::byte> response,
  121. std::size_t& written) noexcept {
  122. namespace purchase_codec = middleware::web_service::messages::opcode901;
  123. purchase_codec::Request purchase;
  124. const bool parsed = purchase_codec::parse_request(message, purchase);
  125. std::array<char, kPurchaseLineCapacity> line{};
  126. const int length =
  127. parsed ? std::snprintf(line.data(),
  128. line.size(),
  129. "ev=ws901 stage=purchase result=refuse vendor=%d sale=%d present=%u",
  130. static_cast<int>(purchase.vendorIndex),
  131. static_cast<int>(purchase.saleIndex),
  132. purchase.hasClock ? 1U : 0U)
  133. : std::snprintf(line.data(),
  134. line.size(),
  135. "ev=ws901 stage=purchase result=refuse reason=parse");
  136. if (length > 0) {
  137. core::log::write(core::log::Channel::server,
  138. core::log::Level::error,
  139. {line.data(), static_cast<std::size_t>(length)});
  140. }
  141. middleware::web_service::StatusResponse status{};
  142. status.code = kPurchaseRefusedCode;
  143. // The trailing bool drives a local action effect on the client, so it stays clear.
  144. status.trailingBool = false;
  145. return middleware::web_service::encode_response(
  146. message,
  147. middleware::web_service::ResponseShape::statusPairWithBool,
  148. status,
  149. response,
  150. written);
  151. }
  152. /** Accepts one affordable, unlocked-tier artifact mod and reports the local purchase effect. */
  153. [[nodiscard]] bool purchase_artifact_mod(const middleware::web_service::Message& message,
  154. std::span<std::byte> response,
  155. std::size_t& written,
  156. Outcome& outcome) noexcept {
  157. namespace purchase_codec = middleware::web_service::messages::opcode901;
  158. purchase_codec::Request purchase{};
  159. if (!purchase_codec::parse_request(message, purchase)
  160. || purchase.vendorIndex != kArtifactVendorIndex || purchase.saleIndex < 0
  161. || purchase.saleIndex
  162. >= static_cast<std::int16_t>(
  163. state::progression::seasonal_experience::kArtifactSaleCount)) {
  164. return false;
  165. }
  166. const auto saleIndex = static_cast<std::uint16_t>(purchase.saleIndex);
  167. if (saleIndex == 5) {
  168. state::ArtifactResetResult reset{};
  169. if (!state::reset_artifact(kArtifactResetGlimmerCost, reset)) {
  170. return false;
  171. }
  172. middleware::web_service::StatusResponse status{};
  173. status.trailingBool = true;
  174. const bool encoded = middleware::web_service::encode_response(
  175. message,
  176. middleware::web_service::ResponseShape::statusPairWithBool,
  177. status,
  178. response,
  179. written);
  180. outcome.hasArtifactReset = encoded;
  181. if (encoded) {
  182. outcome.artifactReset = reset;
  183. }
  184. return encoded;
  185. }
  186. auto* mutation = emplace_mutation<state::PendingArtifactPurchase>(outcome);
  187. if (mutation == nullptr || !state::prepare_artifact_mod_unlock(saleIndex, *mutation)) {
  188. clear_mutation(outcome);
  189. return false;
  190. }
  191. std::array<char, kPurchaseLineCapacity> line{};
  192. const int length =
  193. std::snprintf(line.data(),
  194. line.size(),
  195. "ev=ws901 stage=artifact result=ok vendor=%d sale=%d",
  196. static_cast<int>(purchase.vendorIndex),
  197. static_cast<int>(purchase.saleIndex));
  198. if (length > 0) {
  199. core::log::write(core::log::Channel::server,
  200. core::log::Level::info,
  201. {line.data(), static_cast<std::size_t>(length)});
  202. }
  203. middleware::web_service::StatusResponse status{};
  204. status.trailingBool = true;
  205. const bool encoded = middleware::web_service::encode_response(
  206. message,
  207. middleware::web_service::ResponseShape::statusPairWithBool,
  208. status,
  209. response,
  210. written);
  211. if (!encoded) {
  212. clear_mutation(outcome);
  213. return false;
  214. }
  215. return true;
  216. }
  217. /**
  218. * Answers a request whose own codec refused with the bare correlated echo.
  219. * The Client matches on the echoed transaction id. A missing body is worse than a thin one. It
  220. * under-runs the decoder and takes the BAP connection down.
  221. * @param message Parsed request whose correlation fields are echoed.
  222. * @param response Svc-11 response-body storage owned by the caller.
  223. * @param written Gets the encoded response-body size in bytes.
  224. * @return True when the echo fits.
  225. */
  226. bool encode_echo(const middleware::web_service::Message& message,
  227. std::span<std::byte> response,
  228. std::size_t& written) noexcept {
  229. std::array<char, kEchoLineCapacity> line{};
  230. const int count = std::snprintf(
  231. line.data(), line.size(), "ev=ws stage=body result=echo opcode=%u", message.opcode);
  232. if (count > 0) {
  233. core::log::write(core::log::Channel::server,
  234. core::log::Level::warn,
  235. {line.data(), static_cast<std::size_t>(count)});
  236. }
  237. namespace ws = middleware::web_service;
  238. return ws::encode_response(
  239. message, ws::ResponseShape::generic, ws::StatusResponse{}, response, written);
  240. }
  241. /** Narrow semantic result from the prefix of reflected WS-701 schema 0x80807603. */
  242. struct ProfileSetupMarker {
  243. bool present{};
  244. bool completed{};
  245. };
  246. /** Reads the presence bit that precedes every optional WS-701 schema node. */
  247. [[nodiscard]] bool read_ws701_presence(middleware::encoding::bits::Reader& reader,
  248. bool& present) noexcept {
  249. std::uint64_t value = 0;
  250. if (!reader.read(1, value)) {
  251. return false;
  252. }
  253. present = value != 0;
  254. return true;
  255. }
  256. /** Consumes one optional fixed-width field without retaining it. */
  257. [[nodiscard]] bool skip_ws701_optional(middleware::encoding::bits::Reader& reader,
  258. std::size_t widthBits) noexcept {
  259. bool present = false;
  260. return read_ws701_presence(reader, present) && (!present || reader.skip(widthBits));
  261. }
  262. /**
  263. * Reads only enough of WS-701 schema 0x80807603 to reach preference path 0.1.1.0.
  264. *
  265. * PR #71 maps that first preference scalar as the one-bit profile-setup marker. Everything after
  266. * it belongs to the broader settings-write implementation and is deliberately left to that work.
  267. * This function therefore validates the complete prefix, not the remainder of the request.
  268. */
  269. [[nodiscard]] bool parse_profile_setup_marker(const middleware::web_service::Message& message,
  270. ProfileSetupMarker& output) noexcept {
  271. output = {};
  272. if (message.opcode != middleware::web_service::messages::opcode701::kOpcode) {
  273. return false;
  274. }
  275. middleware::encoding::bits::Reader reader(message.payload);
  276. bool present = false;
  277. // 0.0? client metadata.
  278. if (!read_ws701_presence(reader, present)) {
  279. return false;
  280. }
  281. if (present) {
  282. // 0.0.0? [128] optional 64-bit publicity expiries.
  283. bool publicityPresent = false;
  284. if (!read_ws701_presence(reader, publicityPresent)) {
  285. return false;
  286. }
  287. if (publicityPresent) {
  288. for (std::size_t index = 0; index < 128; ++index) {
  289. if (!skip_ws701_optional(reader, 64)) {
  290. return false;
  291. }
  292. }
  293. }
  294. // 0.0.1? [13] required 32-bit seen-message values.
  295. bool seenMessagesPresent = false;
  296. if (!read_ws701_presence(reader, seenMessagesPresent)
  297. || (seenMessagesPresent && !reader.skip(13U * 32U))) {
  298. return false;
  299. }
  300. }
  301. // 0.1? account data.
  302. bool accountPresent = false;
  303. if (!read_ws701_presence(reader, accountPresent)) {
  304. return false;
  305. }
  306. if (!accountPresent) {
  307. return true;
  308. }
  309. // 0.1.0? [2] optional calibration vectors, each containing two required real32 values.
  310. bool calibrationPresent = false;
  311. if (!read_ws701_presence(reader, calibrationPresent)) {
  312. return false;
  313. }
  314. if (calibrationPresent) {
  315. for (std::size_t index = 0; index < 2; ++index) {
  316. bool vectorPresent = false;
  317. if (!read_ws701_presence(reader, vectorPresent)
  318. || (vectorPresent && !reader.skip(2U * 32U))) {
  319. return false;
  320. }
  321. }
  322. }
  323. // 0.1.1? preference record.
  324. bool preferencesPresent = false;
  325. if (!read_ws701_presence(reader, preferencesPresent)) {
  326. return false;
  327. }
  328. if (!preferencesPresent) {
  329. return true;
  330. }
  331. // 0.1.1.0? one-bit profile-setup marker.
  332. if (!read_ws701_presence(reader, output.present)) {
  333. return false;
  334. }
  335. if (!output.present) {
  336. return true;
  337. }
  338. std::uint64_t completed = 0;
  339. if (!reader.read(1, completed)) {
  340. return false;
  341. }
  342. output.completed = completed != 0;
  343. return true;
  344. }
  345. bool encode_resident_dependent_refusal(std::span<const std::byte> request,
  346. std::span<std::byte> response,
  347. std::size_t& written,
  348. bool& refused) noexcept {
  349. written = 0;
  350. refused = false;
  351. middleware::web_service::Message message;
  352. if (!middleware::web_service::parse_request(request, message)
  353. || !std::binary_search(
  354. kResidentDependentOpcodes.begin(), kResidentDependentOpcodes.end(), message.opcode)) {
  355. return true;
  356. }
  357. refused = true;
  358. middleware::web_service::ResponseShape shape{};
  359. resolve_response_shape(message.opcode, shape);
  360. middleware::web_service::StatusResponse status{};
  361. status.code = kRefusedStatus;
  362. return middleware::web_service::encode_response(message, shape, status, response, written)
  363. || encode_echo(message, response, written);
  364. }
  365. /**
  366. * Parses one request, prepares any action it names, and encodes the reply that reports it.
  367. * @param request Whole decrypted svc-10 body.
  368. * @param response Svc-11 response-body storage owned by the caller.
  369. * @param written Gets the encoded response-body size, or zero when the header does not parse.
  370. * @param outcome Gets the prepared action for the caller to publish, and is left empty when
  371. * the action was refused or the reply could not be encoded.
  372. * @return False only when the envelope header does not parse.
  373. */
  374. bool consume(std::span<const std::byte> request,
  375. std::span<std::byte> response,
  376. std::size_t& written,
  377. Outcome& outcome) noexcept {
  378. written = 0;
  379. outcome = {};
  380. middleware::web_service::Message message;
  381. if (!middleware::web_service::parse_request(request, message)) {
  382. core::log::write(
  383. core::log::Channel::server, core::log::Level::warn, "ev=ws stage=parse result=fail");
  384. return false;
  385. }
  386. if (message.opcode == middleware::web_service::messages::opcode702::kOpcode) {
  387. note_character_writeback(message);
  388. }
  389. if (message.opcode == middleware::web_service::messages::opcode205::kOpcode) {
  390. state::InvestmentState investment{};
  391. return (state::investment_snapshot(investment)
  392. && middleware::web_service::messages::opcode205::encode_response(
  393. message, investment, next_family5_clock(), response, written))
  394. || encode_echo(message, response, written);
  395. }
  396. if (message.opcode == middleware::web_service::messages::opcode503::kOpcode) {
  397. middleware::web_service::messages::opcode503::Request bootstrap;
  398. const bool parsed =
  399. middleware::web_service::messages::opcode503::parse_request(message, bootstrap);
  400. // The request's own key is echoed and adopted. An authored id here costs the ship and the
  401. // banner.
  402. if (!bootstrap.hasPrimarySoid) {
  403. bootstrap.primarySoid = state::account_snapshot().primarySoid;
  404. }
  405. state::InvestmentState investment{};
  406. if (!parsed || !state::investment_snapshot(investment)
  407. || !middleware::web_service::messages::opcode503::encode_response(
  408. message, bootstrap, investment, next_family5_clock(), response, written)) {
  409. return encode_echo(message, response, written);
  410. }
  411. if (bootstrap.hasPrimarySoid && !state::set_primary_soid(bootstrap.primarySoid)) {
  412. core::log::write(core::log::Channel::server,
  413. core::log::Level::warn,
  414. "ev=ws503 stage=adopt result=fail");
  415. }
  416. return true;
  417. }
  418. if (message.opcode == middleware::web_service::messages::opcode501::kOpcode) {
  419. // Returns a SOID family three already publishes. The request body is not parsed.
  420. const std::uint64_t characterSoid =
  421. state::account::selected_character_soid(state::account_snapshot());
  422. return middleware::web_service::messages::opcode501::encode_response(
  423. message, characterSoid, response, written)
  424. || encode_echo(message, response, written);
  425. }
  426. // The artifact vendor is answered here. Every other vendor purchase falls through to the
  427. // shared response-shape path, which runs the action and answers its status: an action that
  428. // prepared no mutation is answered with the refused code.
  429. if (message.opcode == middleware::web_service::messages::opcode901::kOpcode
  430. && names_artifact_vendor(message)) {
  431. return purchase_artifact_mod(message, response, written, outcome)
  432. || refuse_purchase(message, response, written)
  433. || encode_echo(message, response, written);
  434. }
  435. if (message.opcode == middleware::web_service::messages::opcode601::kOpcode) {
  436. return middleware::web_service::messages::opcode601::encode_response(
  437. message, response, written)
  438. || encode_echo(message, response, written);
  439. }
  440. // A subscribe whose body does not parse is still answered; only the subscription is dropped.
  441. middleware::queuez::Subscription subscription;
  442. const bool subscribes =
  443. message.opcode == middleware::web_service::messages::opcode206::kOpcode
  444. && middleware::web_service::messages::opcode206::parse_request(message, subscription);
  445. // The action runs before its reply is encoded, because the reply reports whether it worked.
  446. // Most actions fill the outcome only after preparing a whole transition. WS-701 also accepts
  447. // a valid no-op heartbeat, so that one success is tracked separately from mutation presence.
  448. bool dispatched = true;
  449. bool acceptedWithoutMutation = false;
  450. bool profileSetupRefused = false;
  451. if (message.opcode == middleware::web_service::messages::opcode1801::kOpcode) {
  452. claim_record(message, outcome);
  453. } else if (message.opcode == middleware::web_service::messages::opcode504::kOpcode) {
  454. select_character(message, outcome);
  455. } else if (message.opcode == kItemDismantleOpcode) {
  456. dismantle_item(message, outcome);
  457. } else if (message.opcode == kEquipOpcode) {
  458. mutate_equipment(message, false, outcome);
  459. } else if (message.opcode == kUnequipOpcode) {
  460. mutate_equipment(message, true, outcome);
  461. } else if (message.opcode == middleware::web_service::messages::opcode801::kOpcode) {
  462. mutate_subclass_selection(message, outcome);
  463. } else if (message.opcode == middleware::web_service::messages::opcode1821::kOpcode) {
  464. equip_title(message, outcome);
  465. } else if (message.opcode == middleware::web_service::messages::opcode903::kOpcode) {
  466. mutate_socket_plug(message, outcome);
  467. } else if (message.opcode == middleware::web_service::messages::opcode1901::kOpcode) {
  468. mutate_equipped_socket_plug(message, outcome);
  469. } else if (message.opcode == kItemStateOpcode) {
  470. mutate_item_state(message, outcome);
  471. } else if (message.opcode == middleware::web_service::messages::opcode701::kOpcode) {
  472. const state::SettingsUpdateDisposition disposition = mutate_settings(message, outcome);
  473. acceptedWithoutMutation = disposition == state::SettingsUpdateDisposition::acceptedNoChange;
  474. // The completion marker is applied here. The shared status path below reports the result.
  475. ProfileSetupMarker marker{};
  476. const bool parsed = parse_profile_setup_marker(message, marker);
  477. if (!parsed) {
  478. // Preserve Sunrise's existing WS-701 success behavior outside this narrow feature.
  479. // PR #71 owns complete settings-write validation and can later subsume this prefix.
  480. core::log::write(core::log::Channel::server,
  481. core::log::Level::warn,
  482. "ev=ws701 stage=profile_setup result=ignored reason=prefix_parse");
  483. } else if (marker.present && marker.completed) {
  484. if (!state::complete_profile_setup()) {
  485. profileSetupRefused = true;
  486. } else {
  487. core::log::write(core::log::Channel::server,
  488. core::log::Level::info,
  489. "ev=ws701 stage=profile_setup result=complete marker=1");
  490. }
  491. }
  492. } else if (message.opcode == kItemAcquisitionOpcode) {
  493. acquire_item(message, outcome);
  494. } else if (message.opcode == middleware::web_service::messages::opcode2400::kOpcode) {
  495. claim_season_pass_reward(message, outcome);
  496. } else if (message.opcode == middleware::web_service::messages::opcode901::kOpcode) {
  497. purchase_item(message, outcome);
  498. } else if (message.opcode == middleware::web_service::messages::opcode904::kOpcode) {
  499. acquire_quest(message, outcome);
  500. } else {
  501. dispatched = false;
  502. }
  503. const bool prepared = outcome.hasSelectedCharacter || outcome.hasTitleEquip
  504. || outcome.hasRecordClaim || has_mutation(outcome);
  505. middleware::web_service::ResponseShape shape{};
  506. resolve_response_shape(message.opcode, shape);
  507. middleware::web_service::StatusResponse status{};
  508. if ((dispatched && !prepared && !acceptedWithoutMutation) || profileSetupRefused) {
  509. status.code = kRefusedStatus;
  510. }
  511. if (!middleware::web_service::encode_response(message, shape, status, response, written)) {
  512. // The echo carries no status, so nothing may be published against it.
  513. outcome = {};
  514. return encode_echo(message, response, written);
  515. }
  516. if (subscribes) {
  517. // Publish the subscription only after its correlated response is complete.
  518. outcome.hasSubscription = true;
  519. outcome.subscription = subscription;
  520. }
  521. return true;
  522. }
  523. } // namespace sunrise::server::web_service