From db0b05d17f3f027c396e0f02c8f7971e3ff4a058 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 11:44:52 +0200 Subject: [PATCH 01/20] feat(truapi): refuse a request in a version the host does not know A host refuses a request or subscription start in a version newer than it knows with an `UnsupportedVersion` protocol error, before handling it, and names the newest version it accepts. Handlers now take their decoded request. `on_request` and `on_subscription` infer the request type from the handler, decode the payload, answer bytes that do not decode with `MalformedFrame`, and record the type's `Versioned::LATEST`. The dispatcher checks the version byte after reserving the call, so duplicate ids and early withdrawals are handled as for any other request. Generated handlers no longer carry their own decode step. The TS transport decodes the new error from a codec declared like the Rust enum, settles the refused call as `Unsupported` as it does for `UnsupportedMessage`, and warns with the newest version the host accepts. The Rust decoder reads the known variants from the enum's type information. A host built before this answers such a request with `MalformedFrame`. --- .changeset/request-versions.md | 6 + README.md | 4 + docs/design/truapi-protocol.md | 20 + js/packages/truapi/README.md | 2 + js/packages/truapi/src/client.test.ts | 86 +- js/packages/truapi/src/client.ts | 75 +- .../truapi-codegen/src/rust/dispatcher.rs | 40 +- .../truapi-codegen/tests/golden/dispatcher.rs | 1103 ++--------------- rust/crates/truapi/Cargo.toml | 2 +- rust/crates/truapi/src/dispatcher.rs | 492 ++++++-- rust/crates/truapi/src/frame.rs | 49 +- rust/crates/truapi/src/protocol_error.rs | 19 +- rust/crates/truapi/src/subscription.rs | 67 +- rust/crates/truapi/tests/wire_result_shape.rs | 4 +- 14 files changed, 810 insertions(+), 1159 deletions(-) create mode 100644 .changeset/request-versions.md diff --git a/.changeset/request-versions.md b/.changeset/request-versions.md new file mode 100644 index 0000000000..1b42b18d2e --- /dev/null +++ b/.changeset/request-versions.md @@ -0,0 +1,6 @@ +--- +"@parity/truapi": minor +"@parity/truapi-host": minor +--- + +A host refuses a request or subscription start in a version newer than it knows with an `UnsupportedVersion` protocol error, before handling it, and names the newest version it accepts. The client settles that call as `Unsupported`. A host built before this answers such a request with `MalformedFrame`. diff --git a/README.md b/README.md index c943070e74..8ba2f2f334 100644 --- a/README.md +++ b/README.md @@ -778,6 +778,10 @@ use a different state directory while debugging. - **v0.2**: See [`docs/design/releases/v0.2.md`](docs/design/releases/v0.2.md) for the rationale behind each change. - **v0.3**: current protocol version. +A host refuses a request in a version newer than it knows, and the call +settles as unsupported. See +[Request versions](docs/design/truapi-protocol.md#request-versions). + ## Deploy Pushes to `main` build and deploy: diff --git a/docs/design/truapi-protocol.md b/docs/design/truapi-protocol.md index 0aea8738f5..92e60e3c9a 100644 --- a/docs/design/truapi-protocol.md +++ b/docs/design/truapi-protocol.md @@ -151,3 +151,23 @@ The handshake request carries the protocol (codec) version as a `u8`. On receivi The concrete handshake request, response, and error types are defined in the `truapi` crate. +### Request versions + +Every request payload starts with its version: `V1` is encoded as `0`, `V2` as `1`, and so on. A host can only read the versions it was built with, so a product built against a newer protocol may send a version the host does not know. + +When that happens, the host MUST NOT run the call. It answers with a protocol-error frame (see [Requests](#requests)) carrying: + +```text +V1(UnsupportedVersion { trait_id, method_id, newest_version }) +encoded as [0, 1, trait_id, method_id, newest_version] +``` + +- `trait_id` and `method_id` name the refused call. +- `newest_version` is the newest version the host accepts for that method, as a number: `2` means `V2`. + +The same applies to a subscription's `Start` frame. + +The product treats this like `UnsupportedMessage`: the call fails as unsupported. + +Hosts released before this error existed cannot send it. They answer a version they do not know with `CallError::MalformedFrame`. + diff --git a/js/packages/truapi/README.md b/js/packages/truapi/README.md index ae16b95e15..7ff3dace73 100644 --- a/js/packages/truapi/README.md +++ b/js/packages/truapi/README.md @@ -192,6 +192,8 @@ A host that predates the `Cancel` leg drops the frame with no reply, and the cal The pair `(255, 255)` is reserved for method-independent protocol errors. When a peer rejects an unknown API message with that frame, requests resolve as `CallError.Unsupported` and subscriptions terminate with an `UnsupportedMessageError` cause carrying the unsupported `(trait, method)` pair. +A host also sends this frame when it knows the method but not the request's version, for example when a product is built against a newer protocol than the app. The call then fails the same way as for an unknown method: a request resolves as `CallError.Unsupported`, and a subscription terminates with `UnsupportedMessageError`. + ## Generated files `src/generated/`, `src/playground/codegen/`, and `test/generated/examples/` are produced by [`truapi-codegen`](../../../rust/crates/truapi-codegen/) from the Rust crate and are ignored by git. Do not edit generated files directly. Run from the repo root: diff --git a/js/packages/truapi/src/client.test.ts b/js/packages/truapi/src/client.test.ts index f63dee2c08..42a9cc30f3 100644 --- a/js/packages/truapi/src/client.test.ts +++ b/js/packages/truapi/src/client.test.ts @@ -233,6 +233,19 @@ function unsupportedMessage( return protocolError(requestId, new Uint8Array([0, 0, traitId, methodId])); } +function unsupportedVersion( + requestId: string, + traitId: number, + methodId: number, + newestVersion: number, +): Uint8Array { + // [0] version index, [1] variant index, the refused pair, the newest version. + return protocolError( + requestId, + new Uint8Array([0, 1, traitId, methodId, newestVersion]), + ); +} + describe("generated client transport", () => { it("encodes unit-only enums as a single-byte SCALE discriminant", () => { // Unit-only enums expose a string union on the public API while @@ -387,6 +400,43 @@ describe("generated client transport", () => { expect(fixture.sent).toHaveLength(2); }); + it("settles only the request a refused version names, as unsupported", async () => { + const fixture = providerFixture(); + const transport = createTransport(fixture.provider); + const request = () => + transport.request>({ + ids: { trait: 200, method: 194, kind: "request" }, + payload: new Uint8Array([1]), + decodeResponse: () => ({ success: true, value: "supported" }), + }); + + const refused = request(); + const answered = request(); + const warnings: unknown[][] = []; + const originalWarn = console.warn; + console.warn = (...args: unknown[]) => { + warnings.push(args); + }; + try { + fixture.receive(unsupportedVersion("p:1", 200, 194, 1)); + // A refusal naming another method belongs to another call. + fixture.receive(unsupportedVersion("p:2", 200, 196, 1)); + fixture.receive(wireFrame("p:2", { trait: 200, method: 194 }, MESSAGE_TYPE_RESPONSE)); + } finally { + console.warn = originalWarn; + } + + expect((await refused)._unsafeUnwrapErr()).toEqual({ tag: "Unsupported" }); + expect((await answered)._unsafeUnwrap()).toBe("supported"); + // Nothing is sent again after a refusal. + expect(fixture.sent).toHaveLength(2); + // The newest version is how a developer tells an older app from a + // corrupt request. + expect(String(warnings[0]?.[0])).toContain( + "refused request p:1 for (200, 194): it accepts versions up to V1", + ); + }); + it("does not settle a request from an unmatched or mismatched protocol error", async () => { const fixture = providerFixture(); const transport = createTransport(fixture.provider); @@ -450,6 +500,32 @@ describe("generated client transport", () => { expect(fixture.sent).toHaveLength(1); }); + it("ends a subscription whose start version the host refuses", () => { + const fixture = providerFixture(); + const transport = createTransport(fixture.provider); + const errors: Error[] = []; + const subscription = transport.subscribeRaw({ + ids: { trait: 7, method: 194, kind: "subscription" }, + payload: new Uint8Array([1]), + onReceive: () => {}, + onClose: (error) => errors.push(error), + }); + const originalWarn = console.warn; + console.warn = () => {}; + try { + // A refusal naming another method belongs to another subscription. + fixture.receive(unsupportedVersion(subscription.subscriptionId, 7, 195, 1)); + fixture.receive(unsupportedVersion(subscription.subscriptionId, 7, 194, 1)); + } finally { + console.warn = originalWarn; + } + subscription.unsubscribe(); + + expect(errors).toEqual([new UnsupportedMessageError(7, 194)]); + // The host never started it, so there is nothing to stop. + expect(fixture.sent).toHaveLength(1); + }); + it("terminates a generated subscription when its API is unsupported", () => { const fixture = providerFixture(); const client = createClient(createTransport(fixture.provider)); @@ -489,11 +565,15 @@ describe("generated client transport", () => { // unknown protocol error". const malformedPayloads = [ [new Uint8Array([]), "empty"], - [new Uint8Array([0, 0]), "expected 4 bytes, received 2"], + [new Uint8Array([0, 0]), "truncated"], // trait present, method truncated - [new Uint8Array([0, 0, 194]), "expected 4 bytes, received 3"], + [new Uint8Array([0, 0, 194]), "truncated"], // one trailing byte past a full pair - [new Uint8Array([0, 0, 194, 193, 0]), "expected 4 bytes, received 5"], + [new Uint8Array([0, 0, 194, 193, 0]), "trailing bytes"], + // `UnsupportedVersion` without its newest version + [new Uint8Array([0, 1, 194, 193]), "truncated"], + // one trailing byte past a full `UnsupportedVersion` + [new Uint8Array([0, 1, 194, 193, 2, 0]), "trailing bytes"], ] as const; for (const [payload, message] of malformedPayloads) { diff --git a/js/packages/truapi/src/client.ts b/js/packages/truapi/src/client.ts index a51208ed4e..872aad5cb9 100644 --- a/js/packages/truapi/src/client.ts +++ b/js/packages/truapi/src/client.ts @@ -171,8 +171,36 @@ function pairKey(traitId: number, methodId: number): string { } /** - * Decode `V1(UnsupportedMessage { trait_id, method_id })` from the reserved - * `(255, 255)` address. + * The `V1` protocol errors this build knows, each with its SCALE index, as + * Rust's `ProtocolErrorV1` declares them. + */ +const PROTOCOL_ERRORS_V1 = { + UnsupportedMessage: [0, S.Struct({ traitId: S.u8, methodId: S.u8 })], + UnsupportedVersion: [ + 1, + S.Struct({ traitId: S.u8, methodId: S.u8, newestVersion: S.u8 }), + ], +} as const; + +/** + * `VersionedProtocolError`, the payload on the reserved `(255, 255)` address, + * followed by whatever bytes it leaves unread. + */ +const PROTOCOL_ERROR = S.Tuple( + S.indexedTaggedUnion({ + V1: [0, S.indexedTaggedUnion(PROTOCOL_ERRORS_V1)], + }), + S.Bytes(Infinity), +); + +const KNOWN_PROTOCOL_ERRORS_V1 = new Set( + Object.values(PROTOCOL_ERRORS_V1).map(([index]) => index), +); + +/** + * Decode a protocol error from the reserved `(255, 255)` address. + * `UnsupportedMessage` and `UnsupportedVersion` both mean the peer cannot + * handle the call they name; `newestVersion` is set only for the second. * * `undefined` is a protocol error this build does not know: a version or a * variant index it has never heard of, from a peer built against a later @@ -181,28 +209,34 @@ function pairKey(traitId: number, methodId: number): string { * transport, so a build that rejected an unfamiliar payload here could never be * told anything new without the whole connection dying. * - * A payload this build does recognise stays strict: codec 2 addresses a frame - * by a pair, so `V1(UnsupportedMessage)` is exactly four bytes (version index, - * variant index, then the trait and method the peer could not handle), and a - * truncated or over-long one is corruption rather than a newer peer. + * A payload this build does recognise stays strict: a truncated or over-long + * one is corruption rather than a newer peer. */ -function decodeUnsupportedMessage( +function decodeProtocolError( payload: Uint8Array, -): { traitId: number; methodId: number } | undefined { +): { traitId: number; methodId: number; newestVersion?: number } | undefined { if (payload.length === 0) { throw new Error("Malformed protocol error payload: empty"); } - if (payload[0] !== 0 || (payload.length > 1 && payload[1] !== 0)) { + if ( + payload[0] !== 0 || + (payload.length > 1 && !KNOWN_PROTOCOL_ERRORS_V1.has(payload[1])) + ) { // A version or variant from a later protocol. Its length is unknowable // here, so the remaining bytes are not validated. return undefined; } - if (payload.length !== 4) { - throw new Error( - `Malformed protocol error payload: expected 4 bytes, received ${payload.length}`, - ); + let decoded: ReturnType; + try { + decoded = PROTOCOL_ERROR.dec(payload); + } catch (cause) { + throw new Error("Malformed protocol error payload: truncated", { cause }); + } + const [error, unread] = decoded; + if (unread.length > 0) { + throw new Error("Malformed protocol error payload: trailing bytes"); } - return { traitId: payload[2], methodId: payload[3] }; + return error.value.value; } /** @@ -358,9 +392,9 @@ export function createTransport( payload.traitId === PROTOCOL_ERROR_TRAIT_ID && payload.methodId === PROTOCOL_ERROR_METHOD_ID ) { - let unsupported: { traitId: number; methodId: number } | undefined; + let unsupported: ReturnType; try { - unsupported = decodeUnsupportedMessage(payload.value); + unsupported = decodeProtocolError(payload.value); } catch (error) { onProtocolError(toError(error)); return; @@ -388,6 +422,15 @@ export function createTransport( return; } + if (unsupported.newestVersion !== undefined) { + // The call settles as unsupported either way. The version tells a + // developer whether the app is older than the product or the request + // was corrupt. + console.warn( + `[truapi] the host refused request ${requestId} for (${unsupported.traitId}, ${unsupported.methodId}): it accepts versions up to V${unsupported.newestVersion}`, + ); + } + // Match on the whole pair: a bare method id would alias across traits and // could resolve the wrong pending call. const request = pending.get(requestId); diff --git a/rust/crates/truapi-codegen/src/rust/dispatcher.rs b/rust/crates/truapi-codegen/src/rust/dispatcher.rs index 18297c31aa..5d8cf9947c 100644 --- a/rust/crates/truapi-codegen/src/rust/dispatcher.rs +++ b/rust/crates/truapi-codegen/src/rust/dispatcher.rs @@ -2,9 +2,11 @@ //! incoming frames to the host trait implementation. //! //! For each method the emitter produces an `on_request` (or -//! `on_subscription`) registration that: -//! 1. SCALE-decodes the versioned request wrapper directly from the wire bytes (the wrapper's own -//! variant tag carries its version — there is no outer envelope). +//! `on_subscription`) registration whose handler: +//! 1. Receives the versioned request wrapper, which the framework has decoded from the wire bytes +//! (the wrapper's own variant tag carries its version — there is no outer envelope). The +//! framework refuses a version newer than the wrapper's `Versioned::LATEST`, and answers bytes +//! that do not decode with `MalformedFrame`, before the handler runs. //! 2. Calls the host trait method (which receives the wrapper directly and matches `_::V1(inner)` //! internally). //! 3. SCALE-encodes the versioned response wrapper back onto the wire. @@ -335,7 +337,7 @@ impl MethodEmission { &formatdoc! { r#" let host = {host_expr}; - dispatcher.on_request(wire_table::{ids}, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| {{ + dispatcher.on_request(wire_table::{ids}, move |request_id: String, request: {request_path}, cancel: truapi::CancellationToken| {{ let host = host.clone(); Box::pin(async move {{ "# @@ -347,15 +349,6 @@ impl MethodEmission { 16, &formatdoc! { r#" - let request: {request_path} = match DecodeAll::decode_all(&mut &bytes[..]) {{ - Ok(request) => request, - Err(err) => {{ - let error: truapi::CallError<{error_path}> = - truapi::CallError::MalformedFrame {{ reason: err.to_string() }}; - let result: Result<{response_ty}, truapi::CallError<{error_path}>> = Err(error); - return result.encode(); - }} - }}; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); "# @@ -463,30 +456,13 @@ impl MethodEmission { &formatdoc! { r#" let host = {host_expr}; - dispatcher.on_subscription(wire_table::{ids}, move |request_id: String, bytes: Vec| {{ + dispatcher.on_subscription(wire_table::{ids}, move |request_id: String, request: {start_ty}| {{ let host = host.clone(); Box::pin(async move {{ "# }, ); - write_indented( - out, - 16, - &formatdoc! { - r#" - let request: {start_ty} = match DecodeAll::decode_all(&mut &bytes[..]) {{ - Ok(request) => request, - Err(err) => {{ - let error: truapi::CallError<{error_ty}> = - truapi::CallError::MalformedFrame {{ reason: err.to_string() }}; - return Err(subscription_interrupt(error)); - }} - }}; - "# - }, - ); - writeln!(out, " let target_version = request.version();").unwrap(); write_indented(out, 16, "let cx = CallContext::with_request_id(request_id);\n"); @@ -654,7 +630,7 @@ fn write_imports(out: &mut String, traits: &[&TraitDef]) { r#" use std::sync::Arc; - use parity_scale_codec::{{DecodeAll, Encode}}; + use parity_scale_codec::Encode; use truapi::CallContext; use truapi::api::{{ diff --git a/rust/crates/truapi-codegen/tests/golden/dispatcher.rs b/rust/crates/truapi-codegen/tests/golden/dispatcher.rs index 67b401590b..f0690f6511 100644 --- a/rust/crates/truapi-codegen/tests/golden/dispatcher.rs +++ b/rust/crates/truapi-codegen/tests/golden/dispatcher.rs @@ -9,7 +9,7 @@ use std::sync::Arc; -use parity_scale_codec::{DecodeAll, Encode}; +use parity_scale_codec::Encode; use truapi::CallContext; use truapi::api::{ @@ -101,17 +101,9 @@ where { { let host = host.clone(); - dispatcher.on_subscription(wire_table::ACCOUNT_CONNECTION_STATUS_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::ACCOUNT_CONNECTION_STATUS_SUBSCRIBE, move |request_id: String, request: versioned::account::HostAccountConnectionStatusSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountConnectionStatusSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.connection_status_subscribe(&cx, request).await; @@ -133,18 +125,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_GET_ACCOUNT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_GET_ACCOUNT, move |request_id: String, request: versioned::account::HostAccountGetRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountGetRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -161,18 +144,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_GET_ACCOUNT_ALIAS, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_GET_ACCOUNT_ALIAS, move |request_id: String, request: versioned::account::HostAccountGetAliasRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountGetAliasRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -189,18 +163,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_CREATE_ACCOUNT_PROOF, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_CREATE_ACCOUNT_PROOF, move |request_id: String, request: versioned::account::HostAccountCreateProofRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountCreateProofRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -217,18 +182,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_SIGN_VRF, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_SIGN_VRF, move |request_id: String, request: versioned::account::HostAccountSignVrfRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountSignVrfRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -245,18 +201,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_REGISTER_RING_VRF_KEY, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_REGISTER_RING_VRF_KEY, move |request_id: String, request: versioned::account::HostAccountRegisterRingVrfKeyRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountRegisterRingVrfKeyRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -273,18 +220,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_LIST_RING_VRF_KEYS, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_LIST_RING_VRF_KEYS, move |request_id: String, request: versioned::account::HostAccountListRingVrfKeysRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountListRingVrfKeysRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -301,18 +239,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_RING_VRF_SIGN, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_RING_VRF_SIGN, move |request_id: String, request: versioned::account::HostAccountRingVrfSignRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostAccountRingVrfSignRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -329,18 +258,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_GET_LEGACY_ACCOUNTS, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_GET_LEGACY_ACCOUNTS, move |request_id: String, request: versioned::account::HostGetLegacyAccountsRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostGetLegacyAccountsRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -357,18 +277,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::ACCOUNT_GET_USER_ID, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_GET_USER_ID, move |request_id: String, request: versioned::account::HostGetUserIdRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostGetUserIdRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -385,18 +296,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::ACCOUNT_REQUEST_LOGIN, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ACCOUNT_REQUEST_LOGIN, move |request_id: String, request: versioned::account::HostRequestLoginRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::account::HostRequestLoginRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -419,17 +321,9 @@ where { { let host = host.clone(); - dispatcher.on_subscription(wire_table::CHAIN_FOLLOW_HEAD_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::CHAIN_FOLLOW_HEAD_SUBSCRIBE, move |request_id: String, request: versioned::chain::RemoteChainHeadFollowRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadFollowRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.follow_head_subscribe(&cx, request).await; @@ -451,18 +345,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_GET_HEAD_HEADER, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_HEAD_HEADER, move |request_id: String, request: versioned::chain::RemoteChainHeadHeaderRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadHeaderRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -479,18 +364,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_GET_HEAD_BODY, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_HEAD_BODY, move |request_id: String, request: versioned::chain::RemoteChainHeadBodyRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadBodyRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -507,18 +383,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_GET_HEAD_STORAGE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_HEAD_STORAGE, move |request_id: String, request: versioned::chain::RemoteChainHeadStorageRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadStorageRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -535,18 +402,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_CALL_HEAD, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_CALL_HEAD, move |request_id: String, request: versioned::chain::RemoteChainHeadCallRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadCallRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -563,18 +421,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_UNPIN_HEAD, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_UNPIN_HEAD, move |request_id: String, request: versioned::chain::RemoteChainHeadUnpinRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadUnpinRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -591,18 +440,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_CONTINUE_HEAD, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_CONTINUE_HEAD, move |request_id: String, request: versioned::chain::RemoteChainHeadContinueRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadContinueRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -619,18 +459,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_STOP_HEAD_OPERATION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_STOP_HEAD_OPERATION, move |request_id: String, request: versioned::chain::RemoteChainHeadStopOperationRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainHeadStopOperationRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -647,18 +478,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_GET_SPEC_GENESIS_HASH, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_SPEC_GENESIS_HASH, move |request_id: String, request: versioned::chain::RemoteChainSpecGenesisHashRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainSpecGenesisHashRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -675,18 +497,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_GET_SPEC_CHAIN_NAME, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_SPEC_CHAIN_NAME, move |request_id: String, request: versioned::chain::RemoteChainSpecChainNameRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainSpecChainNameRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -703,18 +516,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_GET_SPEC_PROPERTIES, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_SPEC_PROPERTIES, move |request_id: String, request: versioned::chain::RemoteChainSpecPropertiesRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainSpecPropertiesRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -731,18 +535,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_BROADCAST_TRANSACTION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_BROADCAST_TRANSACTION, move |request_id: String, request: versioned::chain::RemoteChainTransactionBroadcastRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainTransactionBroadcastRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -759,18 +554,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::CHAIN_STOP_TRANSACTION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_STOP_TRANSACTION, move |request_id: String, request: versioned::chain::RemoteChainTransactionStopRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainTransactionStopRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -787,18 +573,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::CHAIN_GET_CHAIN_INFO, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAIN_GET_CHAIN_INFO, move |request_id: String, request: versioned::chain::RemoteChainInfoRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chain::RemoteChainInfoRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -822,18 +599,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_request(wire_table::CHAT_CREATE_ROOM, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAT_CREATE_ROOM, move |request_id: String, request: versioned::chat::HostChatCreateRoomRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chat::HostChatCreateRoomRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -856,18 +624,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_request(wire_table::CHAT_REGISTER_BOT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAT_REGISTER_BOT, move |request_id: String, request: versioned::chat::HostChatRegisterBotRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chat::HostChatRegisterBotRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -890,17 +649,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_subscription(wire_table::CHAT_LIST_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::CHAT_LIST_SUBSCRIBE, move |request_id: String, request: versioned::chat::HostChatListSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::chat::HostChatListSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); if !execution_allowed { @@ -927,18 +678,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_request(wire_table::CHAT_POST_MESSAGE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAT_POST_MESSAGE, move |request_id: String, request: versioned::chat::HostChatPostMessageRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chat::HostChatPostMessageRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -961,17 +703,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_subscription(wire_table::CHAT_ACTION_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::CHAT_ACTION_SUBSCRIBE, move |request_id: String, request: versioned::chat::HostChatActionSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::chat::HostChatActionSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); if !execution_allowed { @@ -998,18 +732,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host; - dispatcher.on_request(wire_table::CHAT_SET_ROOM_FOOTER, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CHAT_SET_ROOM_FOOTER, move |request_id: String, request: versioned::chat::HostChatSetRoomFooterRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::chat::HostChatSetRoomFooterRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -1037,18 +762,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::COIN_PAYMENT_CREATE_PURSE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::COIN_PAYMENT_CREATE_PURSE, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentCreatePurseRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentCreatePurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1065,18 +781,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::COIN_PAYMENT_QUERY_PURSE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::COIN_PAYMENT_QUERY_PURSE, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentQueryPurseRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentQueryPurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1093,17 +800,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::COIN_PAYMENT_REBALANCE_PURSE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::COIN_PAYMENT_REBALANCE_PURSE, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentRebalancePurseRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentRebalancePurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.rebalance_purse(&cx, request).await; @@ -1125,17 +824,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::COIN_PAYMENT_DELETE_PURSE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::COIN_PAYMENT_DELETE_PURSE, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentDeletePurseRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentDeletePurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.delete_purse(&cx, request).await; @@ -1157,18 +848,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::COIN_PAYMENT_CREATE_RECEIVABLE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::COIN_PAYMENT_CREATE_RECEIVABLE, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentCreateReceivableRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentCreateReceivableRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1185,18 +867,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::COIN_PAYMENT_CREATE_CHEQUE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::COIN_PAYMENT_CREATE_CHEQUE, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentCreateChequeRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentCreateChequeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1213,17 +886,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::COIN_PAYMENT_DEPOSIT, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::COIN_PAYMENT_DEPOSIT, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentDepositRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentDepositRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.deposit(&cx, request).await; @@ -1245,17 +910,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::COIN_PAYMENT_REFUND, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::COIN_PAYMENT_REFUND, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentRefundRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentRefundRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.refund(&cx, request).await; @@ -1277,17 +934,9 @@ where } { let host = host; - dispatcher.on_subscription(wire_table::COIN_PAYMENT_LISTEN_FOR_PAYMENT, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::COIN_PAYMENT_LISTEN_FOR_PAYMENT, move |request_id: String, request: versioned::coin_payment::HostCoinPaymentListenForRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::coin_payment::HostCoinPaymentListenForRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.listen_for_payment(&cx, request).await; @@ -1315,18 +964,9 @@ where { { let host = host; - dispatcher.on_request(wire_table::CONTACTS_PICK, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::CONTACTS_PICK, move |request_id: String, request: versioned::contacts::HostContactsPickRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::contacts::HostContactsPickRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1349,18 +989,9 @@ where { { let host = host; - dispatcher.on_request(wire_table::ENTROPY_DERIVE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::ENTROPY_DERIVE, move |request_id: String, request: versioned::entropy::HostDeriveEntropyRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::entropy::HostDeriveEntropyRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1384,18 +1015,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Widget); let host = host; - dispatcher.on_request(wire_table::EXPANDED_CARD_SET_FACE_SHOWN, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::EXPANDED_CARD_SET_FACE_SHOWN, move |request_id: String, request: versioned::expanded_card::HostExpandedCardSetFaceShownRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::expanded_card::HostExpandedCardSetFaceShownRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -1423,18 +1045,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::FUNDING_REQUEST, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::FUNDING_REQUEST, move |request_id: String, request: versioned::funding::HostFundingRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::funding::HostFundingRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1451,17 +1064,9 @@ where } { let host = host; - dispatcher.on_subscription(wire_table::FUNDING_STATUS_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::FUNDING_STATUS_SUBSCRIBE, move |request_id: String, request: versioned::funding::HostFundingStatusSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::funding::HostFundingStatusSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.status_subscribe(&cx, request).await; @@ -1489,18 +1094,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::GAME_REMIND_NEXT_GAME, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::GAME_REMIND_NEXT_GAME, move |request_id: String, request: versioned::game::HostRemindNextGameRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::game::HostRemindNextGameRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1517,18 +1113,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::GAME_CANCEL_NEXT_GAME, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::GAME_CANCEL_NEXT_GAME, move |request_id: String, request: versioned::game::HostCancelNextGameRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::game::HostCancelNextGameRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1551,18 +1138,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::LOCAL_STORAGE_READ, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::LOCAL_STORAGE_READ, move |request_id: String, request: versioned::local_storage::HostLocalStorageReadRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::local_storage::HostLocalStorageReadRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1579,18 +1157,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::LOCAL_STORAGE_WRITE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::LOCAL_STORAGE_WRITE, move |request_id: String, request: versioned::local_storage::HostLocalStorageWriteRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::local_storage::HostLocalStorageWriteRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1607,18 +1176,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::LOCAL_STORAGE_CLEAR, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::LOCAL_STORAGE_CLEAR, move |request_id: String, request: versioned::local_storage::HostLocalStorageClearRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::local_storage::HostLocalStorageClearRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1635,17 +1195,9 @@ where } { let host = host; - dispatcher.on_subscription(wire_table::LOCAL_STORAGE_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::LOCAL_STORAGE_SUBSCRIBE, move |request_id: String, request: versioned::local_storage::HostLocalStorageSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::local_storage::HostLocalStorageSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.subscribe(&cx, request).await; @@ -1673,17 +1225,9 @@ where { { let host = host; - dispatcher.on_subscription(wire_table::LOCALE_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::LOCALE_SUBSCRIBE, move |request_id: String, request: versioned::locale::HostLocaleSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::locale::HostLocaleSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.subscribe(&cx, request).await; @@ -1711,18 +1255,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_CREATE_PURSE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_CREATE_PURSE, move |request_id: String, request: versioned::nft_purse::HostNftPurseCreatePurseRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseCreatePurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1739,18 +1274,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_CREATE_ITEMS, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_CREATE_ITEMS, move |request_id: String, request: versioned::nft_purse::HostNftPurseCreateItemsRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseCreateItemsRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1767,18 +1293,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_QUERY_PURSE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_QUERY_PURSE, move |request_id: String, request: versioned::nft_purse::HostNftPurseQueryPurseRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseQueryPurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1795,18 +1312,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_LIST_PURSES, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_LIST_PURSES, move |request_id: String, request: versioned::nft_purse::HostNftPurseListPursesRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseListPursesRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1823,17 +1331,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::NFT_PURSE_REBALANCE_PURSE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::NFT_PURSE_REBALANCE_PURSE, move |request_id: String, request: versioned::nft_purse::HostNftPurseRebalancePurseRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseRebalancePurseRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.rebalance_purse(&cx, request).await; @@ -1855,18 +1355,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_CREATE_RECEIVE_KEY, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_CREATE_RECEIVE_KEY, move |request_id: String, request: versioned::nft_purse::HostNftPurseCreateReceiveKeyRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseCreateReceiveKeyRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1883,17 +1374,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::NFT_PURSE_LISTEN_FOR_PAYMENT, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::NFT_PURSE_LISTEN_FOR_PAYMENT, move |request_id: String, request: versioned::nft_purse::HostNftPurseListenForPaymentRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseListenForPaymentRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.listen_for_payment(&cx, request).await; @@ -1915,18 +1398,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_CREATE_CHEQUE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_CREATE_CHEQUE, move |request_id: String, request: versioned::nft_purse::HostNftPurseCreateChequeRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseCreateChequeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1943,18 +1417,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::NFT_PURSE_REVOKE_CHEQUE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NFT_PURSE_REVOKE_CHEQUE, move |request_id: String, request: versioned::nft_purse::HostNftPurseRevokeChequeRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseRevokeChequeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -1971,17 +1436,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::NFT_PURSE_DEPOSIT, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::NFT_PURSE_DEPOSIT, move |request_id: String, request: versioned::nft_purse::HostNftPurseDepositRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseDepositRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.deposit(&cx, request).await; @@ -2003,17 +1460,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::NFT_PURSE_REFUND, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::NFT_PURSE_REFUND, move |request_id: String, request: versioned::nft_purse::HostNftPurseRefundRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseRefundRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.refund(&cx, request).await; @@ -2035,17 +1484,9 @@ where } { let host = host; - dispatcher.on_subscription(wire_table::NFT_PURSE_TRANSFER_ITEM, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::NFT_PURSE_TRANSFER_ITEM, move |request_id: String, request: versioned::nft_purse::HostNftPurseTransferItemRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::nft_purse::HostNftPurseTransferItemRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.transfer_item(&cx, request).await; @@ -2073,18 +1514,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::NOTIFICATIONS_SEND_PUSH_NOTIFICATION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NOTIFICATIONS_SEND_PUSH_NOTIFICATION, move |request_id: String, request: versioned::notifications::HostPushNotificationRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::notifications::HostPushNotificationRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2101,18 +1533,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::NOTIFICATIONS_CANCEL_PUSH_NOTIFICATION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::NOTIFICATIONS_CANCEL_PUSH_NOTIFICATION, move |request_id: String, request: versioned::notifications::HostPushNotificationCancelRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::notifications::HostPushNotificationCancelRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2135,17 +1558,9 @@ where { { let host = host.clone(); - dispatcher.on_subscription(wire_table::PAYMENT_BALANCE_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::PAYMENT_BALANCE_SUBSCRIBE, move |request_id: String, request: versioned::payment::HostPaymentBalanceSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::payment::HostPaymentBalanceSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.balance_subscribe(&cx, request).await; @@ -2167,18 +1582,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::PAYMENT_REQUEST, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PAYMENT_REQUEST, move |request_id: String, request: versioned::payment::HostPaymentRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::payment::HostPaymentRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2195,17 +1601,9 @@ where } { let host = host.clone(); - dispatcher.on_subscription(wire_table::PAYMENT_STATUS_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::PAYMENT_STATUS_SUBSCRIBE, move |request_id: String, request: versioned::payment::HostPaymentStatusSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::payment::HostPaymentStatusSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.status_subscribe(&cx, request).await; @@ -2227,18 +1625,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::PAYMENT_TOP_UP, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PAYMENT_TOP_UP, move |request_id: String, request: versioned::payment::HostPaymentTopUpRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::payment::HostPaymentTopUpRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2255,17 +1644,9 @@ where } { let host = host; - dispatcher.on_subscription(wire_table::PAYMENT_TOP_UP_STATUS_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::PAYMENT_TOP_UP_STATUS_SUBSCRIBE, move |request_id: String, request: versioned::payment::HostPaymentTopUpStatusSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::payment::HostPaymentTopUpStatusSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.top_up_status_subscribe(&cx, request).await; @@ -2293,18 +1674,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::PERMISSIONS_REQUEST_DEVICE_PERMISSION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PERMISSIONS_REQUEST_DEVICE_PERMISSION, move |request_id: String, request: versioned::permissions::HostDevicePermissionRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::permissions::HostDevicePermissionRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2321,18 +1693,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::PERMISSIONS_REQUEST_REMOTE_PERMISSION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PERMISSIONS_REQUEST_REMOTE_PERMISSION, move |request_id: String, request: versioned::permissions::RemotePermissionRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::permissions::RemotePermissionRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2349,18 +1712,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::PERMISSIONS_AUTHORIZE_REMOTE_PERMISSION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PERMISSIONS_AUTHORIZE_REMOTE_PERMISSION, move |request_id: String, request: versioned::permissions::RemotePermissionRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::permissions::RemotePermissionRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2377,18 +1731,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::PERMISSIONS_AUTHORIZE_DEVICE_PERMISSION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PERMISSIONS_AUTHORIZE_DEVICE_PERMISSION, move |request_id: String, request: versioned::permissions::HostDevicePermissionRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::permissions::HostDevicePermissionRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2412,17 +1757,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_subscription(wire_table::POCKET_LIST_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::POCKET_LIST_SUBSCRIBE, move |request_id: String, request: versioned::pocket::HostPocketListSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::pocket::HostPocketListSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); if !execution_allowed { @@ -2449,18 +1786,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host; - dispatcher.on_request(wire_table::POCKET_REMOVE_CARD, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::POCKET_REMOVE_CARD, move |request_id: String, request: versioned::pocket::HostPocketRemoveCardRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::pocket::HostPocketRemoveCardRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -2488,17 +1816,9 @@ where { { let host = host.clone(); - dispatcher.on_subscription(wire_table::PREIMAGE_LOOKUP_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::PREIMAGE_LOOKUP_SUBSCRIBE, move |request_id: String, request: versioned::preimage::RemotePreimageLookupSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::preimage::RemotePreimageLookupSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.lookup_subscribe(&cx, request).await; @@ -2520,18 +1840,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::PREIMAGE_SUBMIT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::PREIMAGE_SUBMIT, move |request_id: String, request: versioned::preimage::RemotePreimageSubmitRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::preimage::RemotePreimageSubmitRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2555,17 +1866,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host; - dispatcher.on_subscription(wire_table::RENDERER_ACTION_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::RENDERER_ACTION_SUBSCRIBE, move |request_id: String, request: versioned::renderer::HostRendererActionSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::renderer::HostRendererActionSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); if !execution_allowed { @@ -2597,18 +1900,9 @@ where { { let host = host; - dispatcher.on_request(wire_table::RESOURCE_ALLOCATION_REQUEST, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::RESOURCE_ALLOCATION_REQUEST, move |request_id: String, request: versioned::resource_allocation::HostRequestResourceAllocationRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::resource_allocation::HostRequestResourceAllocationRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2631,18 +1925,9 @@ where { { let host = host; - dispatcher.on_request(wire_table::SCANNER_SCAN, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SCANNER_SCAN, move |request_id: String, request: versioned::scanner::HostScannerScanRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::scanner::HostScannerScanRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2665,18 +1950,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_CREATE_TRANSACTION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_CREATE_TRANSACTION, move |request_id: String, request: versioned::signing::HostCreateTransactionRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostCreateTransactionRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2693,18 +1969,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_CREATE_TRANSACTION_WITH_LEGACY_ACCOUNT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_CREATE_TRANSACTION_WITH_LEGACY_ACCOUNT, move |request_id: String, request: versioned::signing::HostCreateTransactionWithLegacyAccountRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostCreateTransactionWithLegacyAccountRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2721,18 +1988,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_SIGN_RAW_WITH_LEGACY_ACCOUNT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_SIGN_RAW_WITH_LEGACY_ACCOUNT, move |request_id: String, request: versioned::signing::HostSignRawWithLegacyAccountRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostSignRawWithLegacyAccountRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2749,18 +2007,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_SIGN_PAYLOAD_WITH_LEGACY_ACCOUNT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_SIGN_PAYLOAD_WITH_LEGACY_ACCOUNT, move |request_id: String, request: versioned::signing::HostSignPayloadWithLegacyAccountRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostSignPayloadWithLegacyAccountRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2777,18 +2026,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_SIGN_RAW, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_SIGN_RAW, move |request_id: String, request: versioned::signing::HostSignRawRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostSignRawRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2805,18 +2045,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_SIGN_PAYLOAD, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_SIGN_PAYLOAD, move |request_id: String, request: versioned::signing::HostSignPayloadRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostSignPayloadRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2833,18 +2064,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SIGNING_SIGN_RAW_UNWATERMARKED_DEPRECATED, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_SIGN_RAW_UNWATERMARKED_DEPRECATED, move |request_id: String, request: versioned::signing::HostSignRawRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostSignRawRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2861,18 +2083,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::SIGNING_SIGN_RAW_UNWATERMARKED_DEPRECATED_WITH_LEGACY_ACCOUNT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SIGNING_SIGN_RAW_UNWATERMARKED_DEPRECATED_WITH_LEGACY_ACCOUNT, move |request_id: String, request: versioned::signing::HostSignRawWithLegacyAccountRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::signing::HostSignRawWithLegacyAccountRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2895,17 +2108,9 @@ where { { let host = host.clone(); - dispatcher.on_subscription(wire_table::STATEMENT_STORE_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::STATEMENT_STORE_SUBSCRIBE, move |request_id: String, request: versioned::statement_store::RemoteStatementStoreSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::statement_store::RemoteStatementStoreSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.subscribe(&cx, request).await; @@ -2927,18 +2132,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::STATEMENT_STORE_CREATE_PROOF, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::STATEMENT_STORE_CREATE_PROOF, move |request_id: String, request: versioned::statement_store::RemoteStatementStoreCreateProofRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::statement_store::RemoteStatementStoreCreateProofRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2955,18 +2151,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::STATEMENT_STORE_CREATE_PROOF_AUTHORIZED, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::STATEMENT_STORE_CREATE_PROOF_AUTHORIZED, move |request_id: String, request: versioned::statement_store::RemoteStatementStoreCreateProofAuthorizedRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::statement_store::RemoteStatementStoreCreateProofAuthorizedRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -2983,18 +2170,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::STATEMENT_STORE_SUBMIT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::STATEMENT_STORE_SUBMIT, move |request_id: String, request: versioned::statement_store::RemoteStatementStoreSubmitRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::statement_store::RemoteStatementStoreSubmitRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -3017,18 +2195,9 @@ where { { let host = host.clone(); - dispatcher.on_request(wire_table::SYSTEM_HANDSHAKE, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SYSTEM_HANDSHAKE, move |request_id: String, request: versioned::system::HostHandshakeRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::system::HostHandshakeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -3045,18 +2214,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SYSTEM_FEATURE_SUPPORTED, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SYSTEM_FEATURE_SUPPORTED, move |request_id: String, request: versioned::system::HostFeatureSupportedRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::system::HostFeatureSupportedRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -3073,18 +2233,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SYSTEM_NAVIGATE_TO, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SYSTEM_NAVIGATE_TO, move |request_id: String, request: versioned::system::HostNavigateToRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::system::HostNavigateToRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -3101,18 +2252,9 @@ where } { let host = host.clone(); - dispatcher.on_request(wire_table::SYSTEM_HOST_INFO, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SYSTEM_HOST_INFO, move |request_id: String, request: versioned::system::HostInfoRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::system::HostInfoRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -3129,18 +2271,9 @@ where } { let host = host; - dispatcher.on_request(wire_table::SYSTEM_GET_PRODUCT_CONTEXT, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::SYSTEM_GET_PRODUCT_CONTEXT, move |request_id: String, request: versioned::system::HostGetProductContextRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::system::HostGetProductContextRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); let result: Result> = @@ -3163,17 +2296,9 @@ where { { let host = host; - dispatcher.on_subscription(wire_table::THEME_SUBSCRIBE, move |request_id: String, bytes: Vec| { + dispatcher.on_subscription(wire_table::THEME_SUBSCRIBE, move |request_id: String, request: versioned::theme::HostThemeSubscribeRequest| { let host = host.clone(); Box::pin(async move { - let request: versioned::theme::HostThemeSubscribeRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - return Err(subscription_interrupt(error)); - } - }; let target_version = request.version(); let cx = CallContext::with_request_id(request_id); let stream = host.subscribe(&cx, request).await; @@ -3202,18 +2327,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host.clone(); - dispatcher.on_request(wire_table::WORKER_BEGIN_OPERATION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { + dispatcher.on_request(wire_table::WORKER_BEGIN_OPERATION, move |request_id: String, request: versioned::worker::HostWorkerBeginOperationRequest, cancel: truapi::CancellationToken| { let host = host.clone(); Box::pin(async move { - let request: versioned::worker::HostWorkerBeginOperationRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { @@ -3236,18 +2352,9 @@ where { let execution_allowed = dispatcher.allows_execution(ProductExecutionKind::Worker); let host = host; - dispatcher.on_request(wire_table::WORKER_END_OPERATION, move |request_id: String, bytes: Vec, cancel: truapi::CancellationToken| { - let host = host.clone(); - Box::pin(async move { - let request: versioned::worker::HostWorkerEndOperationRequest = match DecodeAll::decode_all(&mut &bytes[..]) { - Ok(request) => request, - Err(err) => { - let error: truapi::CallError = - truapi::CallError::MalformedFrame { reason: err.to_string() }; - let result: Result> = Err(error); - return result.encode(); - } - }; + dispatcher.on_request(wire_table::WORKER_END_OPERATION, move |request_id: String, request: versioned::worker::HostWorkerEndOperationRequest, cancel: truapi::CancellationToken| { + let host = host.clone(); + Box::pin(async move { let target_version = request.version(); let cx = CallContext::with_parts(request_id, cancel); if !execution_allowed { diff --git a/rust/crates/truapi/Cargo.toml b/rust/crates/truapi/Cargo.toml index f7867ddae3..039e4741a5 100644 --- a/rust/crates/truapi/Cargo.toml +++ b/rust/crates/truapi/Cargo.toml @@ -105,7 +105,7 @@ scale-decode = { workspace = true, features = ["derive"], optional = true } # Metadata decoding backs allowance registration, which both the native and the # wasm host perform, so these are not target-gated. frame-metadata = { workspace = true, features = ["std", "current", "decode"], optional = true } -scale-info = { workspace = true, features = ["decode"], optional = true } +scale-info = { workspace = true, features = ["decode", "derive"], optional = true } serde = { workspace = true, features = ["derive"], optional = true } serde_json = { workspace = true, optional = true } thiserror = { workspace = true, optional = true } diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index a52bb8095f..4548e02cb2 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -12,17 +12,17 @@ use std::{ sync::{Arc, Mutex}, }; -use futures::future::BoxFuture; -use parity_scale_codec::Encode; -use tracing::{error, instrument}; -use truapi::CancellationToken; +use futures::future::{self, BoxFuture}; +use parity_scale_codec::{Decode, DecodeAll, Encode}; +use tracing::{debug, error, instrument}; +use truapi::{CancellationToken, versioned::Versioned}; use crate::{ frame::{ MESSAGE_TYPE_CANCEL, MESSAGE_TYPE_INTERRUPT, MESSAGE_TYPE_REQUEST, MESSAGE_TYPE_RESPONSE, MESSAGE_TYPE_START, MESSAGE_TYPE_STOP, PROTOCOL_ERROR_KEY, PROTOCOL_ERROR_METHOD_ID, PROTOCOL_ERROR_TRAIT_ID, Payload, ProtocolErrorV1, ProtocolMessage, VersionedProtocolError, - encode_cancelled_response, + encode_cancelled_response, encode_malformed_frame_error, }, generated::wire_table::MethodIds, subscription::{Spawner, SubscriptionManager, SubscriptionStream}, @@ -55,15 +55,63 @@ pub type SubscriptionHandler = Arc< /// A registered request handler plus the discriminants it replies on. pub struct RequestEntry { ids: MethodIds, + newest_version: u8, handler: RequestHandler, } /// A registered subscription handler plus the discriminants its frames carry. pub struct SubscriptionEntry { ids: MethodIds, + newest_version: u8, handler: SubscriptionHandler, } +/// The protocol error answering a request in a version newer than +/// `newest_version`, the newest its handler decodes. A request payload is its +/// versioned wrapper, so its first byte is the variant index, one less than the +/// version. +fn unsupported_version( + ids: MethodIds, + newest_version: u8, + payload: &[u8], +) -> Option { + let index = *payload.first()?; + if index < newest_version { + return None; + } + // The first byte is all a refusal reads, so a corrupt payload is refused + // too. An implausible version here tells the two apart. + debug!( + trait_id = ids.trait_id, + method_id = ids.method_id, + version = u16::from(index) + 1, + newest_version, + "refusing a request in a version this host does not know" + ); + Some(VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: ids.trait_id, + method_id: ids.method_id, + newest_version, + })) +} + +/// Answer `request_id` on the reserved protocol-error address. +fn send_protocol_error( + transport: &dyn Transport, + request_id: String, + error: VersionedProtocolError, +) { + transport.send(ProtocolMessage { + request_id, + payload: Payload { + trait_id: PROTOCOL_ERROR_TRAIT_ID, + method_id: PROTOCOL_ERROR_METHOD_ID, + message_type: MESSAGE_TYPE_RESPONSE, + value: error.encode(), + }, + }); +} + /// Routes incoming protocol messages to registered handlers, keyed on the /// numeric `(trait, method)` wire discriminant pair. pub struct Dispatcher { @@ -197,15 +245,30 @@ impl Dispatcher { /// entry if any; callers (the generated `dispatcher::register`) should /// treat `Some` as a programming error since each discriminant pair must /// own exactly one handler. - pub fn on_request(&mut self, ids: MethodIds, handler: F) -> Option + /// + /// The handler takes the decoded `Request`. Without running it, the + /// dispatcher answers a version newer than `Request::LATEST` with an + /// `UnsupportedVersion` protocol error, and bytes that do not decode with + /// `MalformedFrame`. + pub fn on_request(&mut self, ids: MethodIds, handler: F) -> Option where - F: Fn(String, Vec, CancellationToken) -> BoxFuture<'static, Vec> + Request: Versioned + Decode + 'static, + F: Fn(String, Request, CancellationToken) -> BoxFuture<'static, Vec> + Send + Sync + 'static, { - self.by_request - .insert((ids.trait_id, ids.method_id), RequestEntry { ids, handler: Arc::new(handler) }) + let handler: RequestHandler = + Arc::new(move |request_id, bytes, cancel| match Request::decode_all(&mut &bytes[..]) { + Ok(request) => handler(request_id, request, cancel), + Err(error) => { + Box::pin(future::ready(encode_malformed_frame_error(error.to_string()))) + }, + }); + self.by_request.insert( + (ids.trait_id, ids.method_id), + RequestEntry { ids, newest_version: Request::LATEST, handler }, + ) } /// Register a subscription handler, keyed on @@ -213,16 +276,32 @@ impl Dispatcher { /// address — [`dispatch`](Self::dispatch) checks its `message_type` and /// routes it to [`SubscriptionManager::handle_stop`] directly, without /// invoking this handler. Returns the previously registered entry if any. - pub fn on_subscription(&mut self, ids: MethodIds, handler: F) -> Option + /// + /// The handler takes the decoded `Start` payload, which the dispatcher + /// checks as for [`on_request`](Self::on_request), ending the stream with a + /// `MalformedFrame` interrupt when it does not decode. + pub fn on_subscription( + &mut self, + ids: MethodIds, + handler: F, + ) -> Option where - F: Fn(String, Vec) -> BoxFuture<'static, Result>> + Request: Versioned + Decode + 'static, + F: Fn(String, Request) -> BoxFuture<'static, Result>> + Send + Sync + 'static, { + let handler: SubscriptionHandler = + Arc::new(move |request_id, bytes| match Request::decode_all(&mut &bytes[..]) { + Ok(request) => handler(request_id, request), + Err(error) => { + Box::pin(future::ready(Err(encode_malformed_frame_error(error.to_string())))) + }, + }); self.by_start.insert( (ids.trait_id, ids.method_id), - SubscriptionEntry { ids, handler: Arc::new(handler) }, + SubscriptionEntry { ids, newest_version: Request::LATEST, handler }, ) } @@ -288,6 +367,15 @@ impl Dispatcher { }, Reservation::AlreadyWithdrawn => encode_cancelled_response(), Reservation::Start(cancel) => { + // Refused before the handler runs, so no `Cancel` can land in + // between and the release has nothing to report. + if let Some(error) = + unsupported_version(entry.ids, entry.newest_version, &message.payload.value) + { + self.release_request(&request_id); + send_protocol_error(transport.as_ref(), request_id, error); + return; + } let value = (entry.handler)(request_id.clone(), message.payload.value, cancel).await; // The single terminal `Response` is how a peer learns its @@ -335,6 +423,15 @@ impl Dispatcher { // subscription instead of racing the registration. let request_id = message.request_id.clone(); let token = self.subscriptions.reserve(request_id.clone()); + // Refused the way a `Start` that fails to decode is: the reservation + // has already replaced any live subscription under this id. + if let Some(error) = + unsupported_version(entry.ids, entry.newest_version, &message.payload.value) + { + self.subscriptions.cancel_reservation(token); + send_protocol_error(transport.as_ref(), request_id, error); + return; + } let result = (entry.handler)(request_id, message.payload.value).await; match result { Ok(stream) => { @@ -375,19 +472,14 @@ impl Dispatcher { }); // A codec 2 peer that asked for something unimplemented can read // the answer, and dropping it would leave the peer waiting forever. - transport.send(ProtocolMessage { - request_id: message.request_id, - payload: Payload { - trait_id: PROTOCOL_ERROR_TRAIT_ID, - method_id: PROTOCOL_ERROR_METHOD_ID, - message_type: MESSAGE_TYPE_RESPONSE, - value: VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedMessage { - trait_id, - method_id, - }) - .encode(), - }, - }); + send_protocol_error( + transport.as_ref(), + message.request_id, + VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedMessage { + trait_id, + method_id, + }), + ); } } @@ -461,6 +553,16 @@ mod tests { use super::*; use crate::frame::{MESSAGE_TYPE_RECEIVE, MESSAGE_TYPE_REQUEST}; use std::sync::Mutex; + // Handlers take real request types: `HostInfoRequest` and + // `HostThemeSubscribeRequest` have one fieldless version, and + // `HostLocalStorageReadRequest` two. + use truapi::{ + v02, + versioned::{ + local_storage::HostLocalStorageReadRequest, system::HostInfoRequest, + theme::HostThemeSubscribeRequest, + }, + }; fn test_spawner() -> Spawner { #[cfg(not(target_arch = "wasm32"))] @@ -505,7 +607,12 @@ mod tests { ) -> ProtocolMessage { ProtocolMessage { request_id: request_id.into(), - payload: Payload { trait_id, method_id, message_type, value: Vec::new() }, + payload: Payload { + trait_id, + method_id, + message_type, + value: HostInfoRequest::V1.encode(), + }, } } @@ -544,7 +651,7 @@ mod tests { let dispatcher = Dispatcher::new(test_spawner()); let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); - let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, Vec::new()); + let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()); futures::executor::block_on(dispatcher.dispatch(frame, transport_dyn)); // 250 != 251 on purpose: the reply must echo the pair in the order it // arrived, and equal values would let a transposition pass. @@ -591,13 +698,13 @@ mod tests { fn dispatch_request_handler_error_emits_response_payload() { let mut dispatcher = Dispatcher::new(test_spawner()); let ids = MethodIds { trait_id: 7, method_id: 200 }; - dispatcher.on_request(ids, |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, |_request_id, _request: HostInfoRequest, _cancel| { // A method's failure is a `Result` inside the response payload, so // an error path still hands back bytes to send. Box::pin(async move { vec![9, 8, 7] }) }); let transport = Arc::new(RecordingTransport::default()); - let frame = make_frame(7, 200, MESSAGE_TYPE_REQUEST, Vec::new()); + let frame = make_frame(7, 200, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()); futures::executor::block_on(dispatcher.dispatch(frame, transport.clone())); let sent = transport.sent(); assert_eq!(sent.len(), 1, "exactly one response expected"); @@ -606,6 +713,198 @@ mod tests { assert_eq!(sent[0].payload.value, vec![9, 8, 7]); } + /// A newer product sends a version this host never learned. It is refused + /// as unsupported, naming the newest version the host decodes, before the + /// handler runs, rather than failing to decode as a malformed frame; a + /// version the host knows still reaches the handler. + #[test] + fn a_request_newer_than_the_handler_decodes_is_refused_with_its_newest_version() { + let mut dispatcher = Dispatcher::new(test_spawner()); + let ids = MethodIds { trait_id: 7, method_id: 200 }; + let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let runs_in_handler = runs.clone(); + dispatcher.on_request( + ids, + move |_request_id, _request: HostLocalStorageReadRequest, _cancel| { + runs_in_handler.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Box::pin(async move { vec![1] }) + }, + ); + let transport = Arc::new(RecordingTransport::default()); + let newest = HostLocalStorageReadRequest::V2(v02::HostLocalStorageReadRequest { + product: None, + key: "k".into(), + }) + .encode(); + // Variant index 2 would be V3, one past the newest this handler decodes. + for (request_id, payload) in [("p:1", vec![2]), ("p:2", newest)] { + let mut frame = make_frame(7, 200, MESSAGE_TYPE_REQUEST, payload); + frame.request_id = request_id.into(); + futures::executor::block_on(dispatcher.dispatch(frame, transport.clone())); + } + + assert_eq!( + transport.sent(), + vec![ + ProtocolMessage { + request_id: "p:1".into(), + payload: Payload { + trait_id: PROTOCOL_ERROR_TRAIT_ID, + method_id: PROTOCOL_ERROR_METHOD_ID, + message_type: MESSAGE_TYPE_RESPONSE, + value: VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: 7, + method_id: 200, + newest_version: 2, + }) + .encode(), + }, + }, + ProtocolMessage { + request_id: "p:2".into(), + payload: Payload { + trait_id: 7, + method_id: 200, + message_type: MESSAGE_TYPE_RESPONSE, + value: vec![1], + }, + }, + ] + ); + assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1); + } + + /// The dispatcher decodes a request before its handler sees it, so bytes + /// that do not decode in a version the handler knows are answered as + /// malformed and never reach it. + #[test] + fn a_request_that_does_not_decode_is_answered_malformed_without_running_the_handler() { + let mut dispatcher = Dispatcher::new(test_spawner()); + let ids = MethodIds { trait_id: 7, method_id: 201 }; + let runs = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let runs_in_handler = runs.clone(); + dispatcher.on_request( + ids, + move |_request_id, _request: HostLocalStorageReadRequest, _cancel| { + runs_in_handler.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Box::pin(async move { vec![1] }) + }, + ); + let transport = Arc::new(RecordingTransport::default()); + // V2, then an invalid `product` option tag. + let payload = vec![1, 0xff]; + let reason = HostLocalStorageReadRequest::decode_all(&mut &payload[..]) + .expect_err("the payload must not decode") + .to_string(); + futures::executor::block_on( + dispatcher + .dispatch(make_frame(7, 201, MESSAGE_TYPE_REQUEST, payload), transport.clone()), + ); + + assert_eq!(transport.sent(), expect_response(7, 201, encode_malformed_frame_error(reason))); + assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 0); + } + + /// A subscription's `Start` carries a version the same way, and a newer one + /// must not start a stream the handler cannot decode. + #[test] + fn a_start_newer_than_the_handler_decodes_is_refused_with_its_newest_version() { + let mut dispatcher = Dispatcher::new(test_spawner()); + let ids = MethodIds { trait_id: 7, method_id: 50 }; + let invoked = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let invoked_in_handler = invoked.clone(); + dispatcher.on_subscription(ids, move |_request_id, _request: HostThemeSubscribeRequest| { + invoked_in_handler.store(true, std::sync::atomic::Ordering::SeqCst); + Box::pin(async move { Ok(Box::pin(futures::stream::empty()) as SubscriptionStream) }) + }); + let transport = Arc::new(RecordingTransport::default()); + let frame = make_frame(7, 50, MESSAGE_TYPE_START, vec![1]); + futures::executor::block_on(dispatcher.dispatch(frame, transport.clone())); + + assert_eq!( + transport.sent(), + vec![ProtocolMessage { + request_id: "p:1".into(), + payload: Payload { + trait_id: PROTOCOL_ERROR_TRAIT_ID, + method_id: PROTOCOL_ERROR_METHOD_ID, + message_type: MESSAGE_TYPE_RESPONSE, + value: VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: 7, + method_id: 50, + newest_version: 1, + }) + .encode(), + }, + }] + ); + assert!(!invoked.load(std::sync::atomic::Ordering::SeqCst)); + } + + /// A refusal is an answer like any other, so a `Cancel` that arrived first + /// still wins, and spends its withdrawal. + #[test] + fn an_early_withdrawal_answers_a_request_in_an_unknown_version_as_cancelled() { + let mut dispatcher = Dispatcher::new(test_spawner()); + let ids = MethodIds { trait_id: 7, method_id: 66 }; + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { + Box::pin(async move { vec![1] }) + }); + let transport = Arc::new(RecordingTransport::default()); + let dispatch = |message_type: u8| { + let transport: Arc = transport.clone(); + futures::executor::block_on( + dispatcher.dispatch(make_frame(7, 66, message_type, vec![1]), transport), + ); + }; + dispatch(MESSAGE_TYPE_CANCEL); + dispatch(MESSAGE_TYPE_REQUEST); + dispatch(MESSAGE_TYPE_REQUEST); + + let refusal = ProtocolMessage { + request_id: "p:1".into(), + payload: Payload { + trait_id: PROTOCOL_ERROR_TRAIT_ID, + method_id: PROTOCOL_ERROR_METHOD_ID, + message_type: MESSAGE_TYPE_RESPONSE, + value: VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: 7, + method_id: 66, + newest_version: 1, + }) + .encode(), + }, + }; + assert_eq!( + transport.sent(), + [expect_response(7, 66, encode_cancelled_response()), vec![refusal]].concat() + ); + } + + /// Two live calls sharing an id leave neither addressable, so a second + /// frame under an id still in flight is dropped whatever its version. A + /// refusal correlated to that id would settle the first call while its + /// handler still runs. + #[test] + fn a_request_in_an_unknown_version_under_an_id_in_flight_is_dropped() { + let mut dispatcher = Dispatcher::new(test_spawner()); + let ids = MethodIds { trait_id: 7, method_id: 67 }; + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { + Box::pin(async move { vec![1] }) + }); + let Reservation::Start(first) = dispatcher.reserve_request("p:1") else { + panic!("the first call registers"); + }; + let transport = Arc::new(RecordingTransport::default()); + futures::executor::block_on( + dispatcher + .dispatch(make_frame(7, 67, MESSAGE_TYPE_REQUEST, vec![1]), transport.clone()), + ); + + assert_eq!(transport.sent(), Vec::::new()); + assert!(!first.is_cancelled()); + } + /// Registering two handlers under the same key must not silently /// overwrite. The contract chosen here is "loud": `on_request` /// returns the previous handler, so callers can detect collisions. @@ -613,11 +912,13 @@ mod tests { fn register_request_twice_returns_previous_handler() { let mut dispatcher = Dispatcher::new(test_spawner()); let ids = MethodIds { trait_id: 7, method_id: 200 }; - let prev = dispatcher - .on_request(ids, |_request_id, _bytes, _cancel| Box::pin(async move { Vec::new() })); + let prev = dispatcher.on_request(ids, |_request_id, _request: HostInfoRequest, _cancel| { + Box::pin(async move { Vec::new() }) + }); assert!(prev.is_none(), "first registration has no predecessor"); - let prev = dispatcher - .on_request(ids, |_request_id, _bytes, _cancel| Box::pin(async move { Vec::new() })); + let prev = dispatcher.on_request(ids, |_request_id, _request: HostInfoRequest, _cancel| { + Box::pin(async move { Vec::new() }) + }); assert!(prev.is_some(), "second registration must return the previous handler"); } @@ -632,7 +933,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 50 }; let invoked = Arc::new(std::sync::atomic::AtomicBool::new(false)); let invoked_in_handler = invoked.clone(); - dispatcher.on_subscription(ids, move |_request_id, _bytes| { + dispatcher.on_subscription(ids, move |_request_id, _request: HostThemeSubscribeRequest| { invoked_in_handler.store(true, std::sync::atomic::Ordering::SeqCst); Box::pin(async move { Ok(Box::pin(futures::stream::empty()) as SubscriptionStream) }) }); @@ -659,7 +960,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 50 }; let invoked = Arc::new(std::sync::atomic::AtomicBool::new(false)); let invoked_in_handler = invoked.clone(); - dispatcher.on_request(ids, move |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { invoked_in_handler.store(true, std::sync::atomic::Ordering::SeqCst); Box::pin(async move { Vec::new() }) }); @@ -687,7 +988,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 60 }; // The handler parks on its token, so the response it produces is // proof the cancel arrived rather than a race the test won by luck. - dispatcher.on_request(ids, move |_request_id, _bytes, cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, cancel| { Box::pin(async move { cancel.cancelled().await; vec![1, 2, 3] @@ -700,8 +1001,10 @@ mod tests { // `join` polls in argument order, so the request reaches its // registration before the cancel looks for it. futures::executor::block_on(futures::future::join( - dispatcher - .dispatch(make_frame(7, 60, MESSAGE_TYPE_REQUEST, Vec::new()), request_transport), + dispatcher.dispatch( + make_frame(7, 60, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + request_transport, + ), dispatcher .dispatch(make_frame(7, 60, MESSAGE_TYPE_CANCEL, Vec::new()), cancel_transport), )); @@ -735,6 +1038,37 @@ mod tests { assert_eq!(decoded, Err(truapi::CallError::Cancelled)); } + /// The dispatcher answers a payload that does not decode before it can name + /// the method's payload types, so the bytes have to decode as any method's + /// response leg, and as a subscription's interrupt leg, whose `Err` arm has + /// the same shape. + #[test] + fn a_malformed_frame_error_decodes_against_real_methods_legs() { + use truapi::versioned::{ + account::{HostAccountGetError, HostAccountGetResponse}, + system::{HostInfoError, HostInfoResponse}, + theme::HostThemeSubscribeError, + }; + + let reason = "bad payload".to_string(); + let bytes = encode_malformed_frame_error(reason.clone()); + let account: Result> = + DecodeAll::decode_all(&mut &bytes[..]).expect("decodes as a response leg"); + let info: Result> = + DecodeAll::decode_all(&mut &bytes[..]).expect("decodes as a response leg"); + let interrupt: Result<(), truapi::CallError> = + DecodeAll::decode_all(&mut &bytes[..]).expect("decodes as an interrupt leg"); + + assert_eq!( + (account, info, interrupt), + ( + Err(truapi::CallError::MalformedFrame { reason: reason.clone() }), + Err(truapi::CallError::MalformedFrame { reason: reason.clone() }), + Err(truapi::CallError::MalformedFrame { reason }), + ) + ); + } + /// A `Cancel` names a call by id alone, so two live calls sharing one id /// would leave neither of them addressable. The second is refused, and /// the first stays the one that id reaches. @@ -765,15 +1099,16 @@ mod tests { fn a_settled_call_leaves_no_entry_behind() { let mut dispatcher = Dispatcher::new(test_spawner()); let ids = MethodIds { trait_id: 7, method_id: 62 }; - dispatcher.on_request(ids, move |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { Box::pin(async move { vec![9, 9] }) }); let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); - futures::executor::block_on( - dispatcher.dispatch(make_frame(7, 62, MESSAGE_TYPE_REQUEST, Vec::new()), transport_dyn), - ); + futures::executor::block_on(dispatcher.dispatch( + make_frame(7, 62, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + transport_dyn, + )); assert!( dispatcher @@ -795,7 +1130,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 63 }; // The handler fires its own token, standing in for an attached // timeout, and answers normally. - dispatcher.on_request(ids, move |_request_id, _bytes, cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, cancel| { Box::pin(async move { cancel.cancel(); vec![9, 9] @@ -803,9 +1138,10 @@ mod tests { }); let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); - futures::executor::block_on( - dispatcher.dispatch(make_frame(7, 63, MESSAGE_TYPE_REQUEST, Vec::new()), transport_dyn), - ); + futures::executor::block_on(dispatcher.dispatch( + make_frame(7, 63, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + transport_dyn, + )); assert_eq!( transport.sent(), expect_response(7, 63, vec![9, 9]), @@ -823,7 +1159,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 64 }; let invocations = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let handler_invocations = invocations.clone(); - dispatcher.on_request(ids, move |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { handler_invocations.fetch_add(1, std::sync::atomic::Ordering::SeqCst); Box::pin(async move { vec![1, 2, 3] }) }); @@ -835,10 +1171,10 @@ mod tests { .dispatch(make_frame(7, 64, MESSAGE_TYPE_CANCEL, Vec::new()), cancel_transport), ); let request_transport: Arc = transport.clone(); - futures::executor::block_on( - dispatcher - .dispatch(make_frame(7, 64, MESSAGE_TYPE_REQUEST, Vec::new()), request_transport), - ); + futures::executor::block_on(dispatcher.dispatch( + make_frame(7, 64, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + request_transport, + )); assert_eq!( invocations.load(std::sync::atomic::Ordering::SeqCst), @@ -862,7 +1198,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 65 }; let invocations = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let handler_invocations = invocations.clone(); - dispatcher.on_request(ids, move |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { handler_invocations.fetch_add(1, std::sync::atomic::Ordering::SeqCst); Box::pin(async move { vec![4, 5, 6] }) }); @@ -870,9 +1206,10 @@ mod tests { let dispatch = |message_type: u8| { let transport: Arc = transport.clone(); - futures::executor::block_on( - dispatcher.dispatch(make_frame(7, 65, message_type, Vec::new()), transport), - ); + futures::executor::block_on(dispatcher.dispatch( + make_frame(7, 65, message_type, HostInfoRequest::V1.encode()), + transport, + )); }; dispatch(MESSAGE_TYPE_CANCEL); dispatch(MESSAGE_TYPE_REQUEST); @@ -904,7 +1241,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 66 }; let invocations = Arc::new(std::sync::atomic::AtomicUsize::new(0)); let handler_invocations = invocations.clone(); - dispatcher.on_request(ids, move |_request_id, _bytes, cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, cancel| { handler_invocations.fetch_add(1, std::sync::atomic::Ordering::SeqCst); Box::pin(async move { cancel.cancelled().await; @@ -919,8 +1256,14 @@ mod tests { // test reports an assertion rather than hanging. let cancel: Arc = transport.clone(); futures::executor::block_on(futures::future::join3( - dispatcher.dispatch(make_frame(7, 66, MESSAGE_TYPE_REQUEST, Vec::new()), first), - dispatcher.dispatch(make_frame(7, 66, MESSAGE_TYPE_REQUEST, Vec::new()), duplicate), + dispatcher.dispatch( + make_frame(7, 66, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + first, + ), + dispatcher.dispatch( + make_frame(7, 66, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + duplicate, + ), dispatcher.dispatch(make_frame(7, 66, MESSAGE_TYPE_CANCEL, Vec::new()), cancel), )); @@ -943,8 +1286,9 @@ mod tests { fn the_oldest_early_withdrawal_is_evicted_once_the_queue_is_full() { let mut dispatcher = Dispatcher::new(test_spawner()); let ids = MethodIds { trait_id: 7, method_id: 65 }; - dispatcher - .on_request(ids, move |_request_id, _bytes, _cancel| Box::pin(async move { vec![7] })); + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { + Box::pin(async move { vec![7] }) + }); let transport = Arc::new(RecordingTransport::default()); // One more than the queue holds, so `p:0` is pushed back out. @@ -989,7 +1333,7 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 61 }; let invoked = Arc::new(std::sync::atomic::AtomicBool::new(false)); let invoked_in_handler = invoked.clone(); - dispatcher.on_request(ids, move |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { invoked_in_handler.store(true, std::sync::atomic::Ordering::SeqCst); Box::pin(async move { Vec::new() }) }); @@ -1013,14 +1357,15 @@ mod tests { fn cancel_does_not_change_the_result_of_a_handler_that_ignores_it() { let mut dispatcher = Dispatcher::new(test_spawner()); let ids = MethodIds { trait_id: 7, method_id: 62 }; - dispatcher.on_request(ids, move |_request_id, _bytes, _cancel| { + dispatcher.on_request(ids, move |_request_id, _request: HostInfoRequest, _cancel| { Box::pin(async move { vec![4, 5] }) }); let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); - futures::executor::block_on( - dispatcher.dispatch(make_frame(7, 62, MESSAGE_TYPE_REQUEST, Vec::new()), transport_dyn), - ); + futures::executor::block_on(dispatcher.dispatch( + make_frame(7, 62, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()), + transport_dyn, + )); let transport_dyn: Arc = transport.clone(); futures::executor::block_on( dispatcher.dispatch(make_frame(7, 62, MESSAGE_TYPE_CANCEL, Vec::new()), transport_dyn), @@ -1041,12 +1386,15 @@ mod tests { let ids = MethodIds { trait_id: 7, method_id: 50 }; let invoked = Arc::new(std::sync::atomic::AtomicBool::new(false)); let invoked_in_handler = invoked.clone(); - dispatcher.on_subscription(ids, move |_request_id, _bytes| { - invoked_in_handler.store(true, std::sync::atomic::Ordering::SeqCst); - Box::pin( - async move { Ok(Box::pin(futures::stream::empty()) as SubscriptionStream) }, - ) - }); + dispatcher.on_subscription( + ids, + move |_request_id, _request: HostThemeSubscribeRequest| { + invoked_in_handler.store(true, std::sync::atomic::Ordering::SeqCst); + Box::pin( + async move { Ok(Box::pin(futures::stream::empty()) as SubscriptionStream) }, + ) + }, + ); let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); let frame = make_frame(7, 50, message_type, Vec::new()); @@ -1071,7 +1419,7 @@ mod tests { let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); for _ in 0..3 { - let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, Vec::new()); + let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()); futures::executor::block_on(dispatcher.dispatch(frame, transport_dyn.clone())); } assert_eq!( diff --git a/rust/crates/truapi/src/frame.rs b/rust/crates/truapi/src/frame.rs index 96c6e7c5ee..ef43678585 100644 --- a/rust/crates/truapi/src/frame.rs +++ b/rust/crates/truapi/src/frame.rs @@ -23,6 +23,7 @@ //! reconstruct string action tags on every frame. use parity_scale_codec::{Decode, Encode, Error as CodecError, Input, Output}; +use scale_info::TypeInfo; use truapi::{ CallError, versioned::{FromLatest, IntoLatest, Versioned}, @@ -64,7 +65,7 @@ pub enum VersionedProtocolError { } /// Protocol errors supported by codec version 1. -#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)] pub enum ProtocolErrorV1 { /// The receiver does not support the incoming message address. Codec 2 /// addresses a frame by `(trait, method)`, so one byte can no longer name @@ -76,6 +77,19 @@ pub enum ProtocolErrorV1 { /// Method discriminant of the unsupported incoming frame. method_id: u8, }, + /// The receiver handles the method but not the version the request was + /// sent in. It rejected the request before handling it, so the sender can + /// send it again in a version the receiver accepts. + #[codec(index = 1)] + UnsupportedVersion { + /// Trait discriminant of the rejected request. + trait_id: u8, + /// Method discriminant of the rejected request. + method_id: u8, + /// Newest request version the receiver accepts for this method, + /// numbered like the `V` variant that carries it. + newest_version: u8, + }, } /// Downgrade a call error's domain payload to the version its caller speaks. @@ -133,6 +147,17 @@ pub fn encode_cancelled_response() -> Vec { Err::<(), CallError<()>>(CallError::Cancelled).encode() } +/// Encode `Err(CallError::MalformedFrame { reason })` for a payload that did +/// not decode. +/// +/// Valid as any request's `Response` and any subscription's `Interrupt` +/// without knowing the method's types, for the same reason as +/// [`encode_cancelled_response`]: both legs are a `Result` whose `Ok` arm is +/// never reached, and `MalformedFrame` carries only its reason. +pub fn encode_malformed_frame_error(reason: String) -> Vec { + Err::<(), CallError<()>>(CallError::MalformedFrame { reason }).encode() +} + /// Encode `Interrupt(Ok(()))`, a subscription's natural (error-free) /// completion. `Ok(())` always encodes as a single `0` byte, so a clean /// interrupt is one byte whatever the method's interrupt type is. Pair it @@ -356,6 +381,16 @@ mod tests { // Trait and method differ here on purpose, so transposing the two // fields cannot pass. assert_eq!((encoded, decoded), (vec![0, 0, 250, 251], Some(error))); + + let error = VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: 250, + method_id: 251, + newest_version: 2, + }); + let encoded = error.encode(); + let decoded = decode_protocol_error_payload(&encoded).expect("decode"); + // [0] versioned index, [1] variant index, trait, method, newest version. + assert_eq!((encoded, decoded), (vec![0, 1, 250, 251, 2], Some(error))); } #[test] @@ -369,11 +404,13 @@ mod tests { // so the protocol-error channel stays extensible. See // `an_unknown_protocol_error_variant_is_tolerated`. for payload in [ - vec![], // no payload at all - vec![0], // version present, variant truncated - vec![0, 0], // no address at all - vec![0, 0, 250], // trait present, method truncated - vec![0, 0, 250, 251, 0], // one trailing byte past a full pair + vec![], // no payload at all + vec![0], // version present, variant truncated + vec![0, 0], // no address at all + vec![0, 0, 250], // trait present, method truncated + vec![0, 0, 250, 251, 0], // one trailing byte past a full pair + vec![0, 1, 250, 251], // newest version truncated + vec![0, 1, 250, 251, 2, 0], // one trailing byte past a full version ] { let message = ProtocolMessage { request_id: "p:1".into(), diff --git a/rust/crates/truapi/src/protocol_error.rs b/rust/crates/truapi/src/protocol_error.rs index 60553db506..cc1d2329f1 100644 --- a/rust/crates/truapi/src/protocol_error.rs +++ b/rust/crates/truapi/src/protocol_error.rs @@ -1,8 +1,9 @@ //! Tolerant decoding of the protocol-error frame payload. use parity_scale_codec::{Decode, Error as CodecError}; +use scale_info::{TypeDef, TypeInfo}; -use crate::frame::VersionedProtocolError; +use crate::frame::{ProtocolErrorV1, VersionedProtocolError}; /// Decode a [`crate::frame::PROTOCOL_ERROR_KEY`] frame's payload. /// @@ -15,7 +16,8 @@ use crate::frame::VersionedProtocolError; /// settle the correlated call as an unspecified protocol failure and carry on. /// /// A payload this build does recognise stays strict: a truncated or over-long -/// `V1(UnsupportedMessage)` is corruption, not a newer peer, and still fails. +/// `V1(UnsupportedMessage)` or `V1(UnsupportedVersion)` is corruption, not a +/// newer peer, and still fails. pub fn decode_protocol_error_payload( payload: &[u8], ) -> Result, CodecError> { @@ -24,8 +26,8 @@ pub fn decode_protocol_error_payload( // A version from a later protocol. (Some(version), _) if *version != 0 => Ok(None), // A `V1` variant from a later protocol. - (Some(_), Some(variant)) if *variant != 0 => Ok(None), - // `V1(UnsupportedMessage)`, the only shape this build knows. + (Some(_), Some(variant)) if !is_known_v1_variant(*variant) => Ok(None), + // A `V1` variant this build knows. _ => { let mut input = payload; let error = VersionedProtocolError::decode(&mut input)?; @@ -36,3 +38,12 @@ pub fn decode_protocol_error_payload( }, } } + +/// Whether `index` encodes a [`ProtocolErrorV1`] variant this build knows, read +/// from the enum itself so a new variant is known the moment it is declared. +fn is_known_v1_variant(index: u8) -> bool { + matches!( + ProtocolErrorV1::type_info().type_def, + TypeDef::Variant(def) if def.variants.iter().any(|variant| variant.index == index) + ) +} diff --git a/rust/crates/truapi/src/subscription.rs b/rust/crates/truapi/src/subscription.rs index 387732a075..7e3a6cc82f 100644 --- a/rust/crates/truapi/src/subscription.rs +++ b/rust/crates/truapi/src/subscription.rs @@ -455,13 +455,14 @@ impl HostInitiatedSubscriptionManager { // silently drop the frame that reports our start as unsupported. if key == PROTOCOL_ERROR_KEY { let frame = match decode_protocol_error_payload(&message.payload.value) { - Ok(Some(VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedMessage { - trait_id, - method_id, - }))) => { + Ok(Some(VersionedProtocolError::V1( + ProtocolErrorV1::UnsupportedMessage { trait_id, method_id } | + ProtocolErrorV1::UnsupportedVersion { trait_id, method_id, .. }, + ))) => { // Only OUR start frame going unsupported ends this render; // an error about any other pair belongs to a different - // subscription. + // subscription. A product refusing the start's version ends + // it the same way. if (trait_id, method_id) != (slot.ids.trait_id, slot.ids.method_id) { return None; } @@ -879,29 +880,37 @@ mod tests { #[test] fn protocol_error_ends_one_host_render_without_echoing_stop() { - let transport_typed = Arc::new(RecordingTransport::new()); - let transport: Arc = transport_typed.clone(); - let manager = HostInitiatedSubscriptionManager::new(); - let mut unsupported = - manager.start::(host_ids(), vec![], transport); - - manager.handle_message(ProtocolMessage { - request_id: "h:1".into(), - payload: Payload { - trait_id: PROTOCOL_ERROR_TRAIT_ID, - method_id: PROTOCOL_ERROR_METHOD_ID, - message_type: MESSAGE_TYPE_RESPONSE, - value: VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedMessage { - trait_id: host_ids().trait_id, - method_id: host_ids().method_id, - }) - .encode(), + for error in [ + ProtocolErrorV1::UnsupportedMessage { + trait_id: host_ids().trait_id, + method_id: host_ids().method_id, }, - }); + ProtocolErrorV1::UnsupportedVersion { + trait_id: host_ids().trait_id, + method_id: host_ids().method_id, + newest_version: 1, + }, + ] { + let transport_typed = Arc::new(RecordingTransport::new()); + let transport: Arc = transport_typed.clone(); + let manager = HostInitiatedSubscriptionManager::new(); + let mut unsupported = + manager.start::(host_ids(), vec![], transport); - assert_eq!(unsupported.next().now_or_never(), Some(Some(Err(CallError::Unsupported)))); - assert_eq!(unsupported.next().now_or_never(), Some(None)); - assert_eq!(transport_typed.sent().len(), 1); + manager.handle_message(ProtocolMessage { + request_id: "h:1".into(), + payload: Payload { + trait_id: PROTOCOL_ERROR_TRAIT_ID, + method_id: PROTOCOL_ERROR_METHOD_ID, + message_type: MESSAGE_TYPE_RESPONSE, + value: VersionedProtocolError::V1(error).encode(), + }, + }); + + assert_eq!(unsupported.next().now_or_never(), Some(Some(Err(CallError::Unsupported)))); + assert_eq!(unsupported.next().now_or_never(), Some(None)); + assert_eq!(transport_typed.sent().len(), 1); + } } #[test] @@ -972,6 +981,12 @@ mod tests { method_id: host_ids().method_id + 1, }) .encode(), + VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: host_ids().trait_id, + method_id: host_ids().method_id + 1, + newest_version: 1, + }) + .encode(), vec![0, 0], ] { manager.handle_message(ProtocolMessage { diff --git a/rust/crates/truapi/tests/wire_result_shape.rs b/rust/crates/truapi/tests/wire_result_shape.rs index 8c1e49ed82..09680a4378 100644 --- a/rust/crates/truapi/tests/wire_result_shape.rs +++ b/rust/crates/truapi/tests/wire_result_shape.rs @@ -450,7 +450,9 @@ fn malformed_result_subscription_start_interrupts_with_malformed_frame() { trait_id: ids.trait_id, method_id: ids.method_id, message_type: MESSAGE_TYPE_START, - value: vec![0xff], + // V1, then an invalid `purse` option tag. A first byte naming a + // later version would be refused as unsupported, not malformed. + value: vec![0x00, 0xff], }, }, transport.clone(), From 5a871485eb1c70ece76d17160dbb891ea92bd577 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 13:25:15 +0200 Subject: [PATCH 02/20] docs(changeset): reword the request versions release note --- .changeset/request-versions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/request-versions.md b/.changeset/request-versions.md index 1b42b18d2e..e794731990 100644 --- a/.changeset/request-versions.md +++ b/.changeset/request-versions.md @@ -3,4 +3,4 @@ "@parity/truapi-host": minor --- -A host refuses a request or subscription start in a version newer than it knows with an `UnsupportedVersion` protocol error, before handling it, and names the newest version it accepts. The client settles that call as `Unsupported`. A host built before this answers such a request with `MalformedFrame`. +If a product sends a request in a version the host doesn't know, the host rejects it with an `UnsupportedVersion` error instead of failing to decode it, and the call fails as `Unsupported`. Older hosts still answer `MalformedFrame`. From 17419e5897152d729868c347a5b7adac39546f7e Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 13:34:35 +0200 Subject: [PATCH 03/20] docs(truapi): reword the unsupported version note in the README --- js/packages/truapi/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js/packages/truapi/README.md b/js/packages/truapi/README.md index 7ff3dace73..1100c01596 100644 --- a/js/packages/truapi/README.md +++ b/js/packages/truapi/README.md @@ -192,7 +192,7 @@ A host that predates the `Cancel` leg drops the frame with no reply, and the cal The pair `(255, 255)` is reserved for method-independent protocol errors. When a peer rejects an unknown API message with that frame, requests resolve as `CallError.Unsupported` and subscriptions terminate with an `UnsupportedMessageError` cause carrying the unsupported `(trait, method)` pair. -A host also sends this frame when it knows the method but not the request's version, for example when a product is built against a newer protocol than the app. The call then fails the same way as for an unknown method: a request resolves as `CallError.Unsupported`, and a subscription terminates with `UnsupportedMessageError`. +The host also uses this frame to reject a request in a version it doesn't know. The product sees the same errors as for an unknown method. ## Generated files From 4a3b108d72c53524f78a77e92e48b6a463765ed1 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:40:38 +0200 Subject: [PATCH 04/20] docs(truapi): reword the unsupported version helper's doc comment --- rust/crates/truapi/src/dispatcher.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index 4548e02cb2..bae58f7ad7 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -66,10 +66,9 @@ pub struct SubscriptionEntry { handler: SubscriptionHandler, } -/// The protocol error answering a request in a version newer than -/// `newest_version`, the newest its handler decodes. A request payload is its -/// versioned wrapper, so its first byte is the variant index, one less than the -/// version. +/// Returns the error to send back when `payload` is in a version newer than +/// `newest_version`. The first byte of a request is its version, starting at +/// 0 for `V1`. fn unsupported_version( ids: MethodIds, newest_version: u8, From e30b2020ad814e54fa3fcfe88abf5c0684429c92 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:48:06 +0200 Subject: [PATCH 05/20] refactor(truapi): name the dispatcher's decoding wrapper apart from the handler it wraps --- rust/crates/truapi/src/dispatcher.rs | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index bae58f7ad7..8c1da31ef1 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -257,16 +257,17 @@ impl Dispatcher { + Sync + 'static, { - let handler: RequestHandler = + let decode_then_handle: RequestHandler = Arc::new(move |request_id, bytes, cancel| match Request::decode_all(&mut &bytes[..]) { Ok(request) => handler(request_id, request, cancel), Err(error) => { - Box::pin(future::ready(encode_malformed_frame_error(error.to_string()))) + let malformed = encode_malformed_frame_error(error.to_string()); + Box::pin(future::ready(malformed)) }, }); self.by_request.insert( (ids.trait_id, ids.method_id), - RequestEntry { ids, newest_version: Request::LATEST, handler }, + RequestEntry { ids, newest_version: Request::LATEST, handler: decode_then_handle }, ) } @@ -291,16 +292,17 @@ impl Dispatcher { + Sync + 'static, { - let handler: SubscriptionHandler = + let decode_then_handle: SubscriptionHandler = Arc::new(move |request_id, bytes| match Request::decode_all(&mut &bytes[..]) { Ok(request) => handler(request_id, request), Err(error) => { - Box::pin(future::ready(Err(encode_malformed_frame_error(error.to_string())))) + let malformed = encode_malformed_frame_error(error.to_string()); + Box::pin(future::ready(Err(malformed))) }, }); self.by_start.insert( (ids.trait_id, ids.method_id), - SubscriptionEntry { ids, newest_version: Request::LATEST, handler }, + SubscriptionEntry { ids, newest_version: Request::LATEST, handler: decode_then_handle }, ) } From 28332f7db737469befe2b22c15bbdf0953ad526e Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:50:54 +0200 Subject: [PATCH 06/20] fix(truapi): let a Cancel that beats a version refusal answer Cancelled --- rust/crates/truapi/src/dispatcher.rs | 33 ++++++++++++++++------------ 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index 8c1da31ef1..bb536cd78d 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -368,24 +368,29 @@ impl Dispatcher { }, Reservation::AlreadyWithdrawn => encode_cancelled_response(), Reservation::Start(cancel) => { - // Refused before the handler runs, so no `Cancel` can land in - // between and the release has nothing to report. if let Some(error) = unsupported_version(entry.ids, entry.newest_version, &message.payload.value) { - self.release_request(&request_id); - send_protocol_error(transport.as_ref(), request_id, error); - return; - } - let value = - (entry.handler)(request_id.clone(), message.payload.value, cancel).await; - // The single terminal `Response` is how a peer learns its - // cancel was heard, so it wins over whatever the handler - // returned. - if self.release_request(&request_id) { - encode_cancelled_response() + // If a `Cancel` arrived in the meantime, it wins, as it + // does after a handler runs. + if self.release_request(&request_id) { + encode_cancelled_response() + } else { + send_protocol_error(transport.as_ref(), request_id, error); + return; + } } else { - value + let value = + (entry.handler)(request_id.clone(), message.payload.value, cancel) + .await; + // The single terminal `Response` is how a peer learns its + // cancel was heard, so it wins over whatever the handler + // returned. + if self.release_request(&request_id) { + encode_cancelled_response() + } else { + value + } } }, }; From ba960d5078eb257abcd790c94d4810853d782b21 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:52:56 +0200 Subject: [PATCH 07/20] refactor(truapi): settle a reserved call's answer in one match --- rust/crates/truapi/src/dispatcher.rs | 42 +++++++++++++--------------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index bb536cd78d..6f0d696ff0 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -368,29 +368,27 @@ impl Dispatcher { }, Reservation::AlreadyWithdrawn => encode_cancelled_response(), Reservation::Start(cancel) => { - if let Some(error) = - unsupported_version(entry.ids, entry.newest_version, &message.payload.value) - { - // If a `Cancel` arrived in the meantime, it wins, as it - // does after a handler runs. - if self.release_request(&request_id) { - encode_cancelled_response() - } else { - send_protocol_error(transport.as_ref(), request_id, error); + let outcome = match unsupported_version( + entry.ids, + entry.newest_version, + &message.payload.value, + ) { + Some(refusal) => Err(refusal), + None => { + Ok((entry.handler)(request_id.clone(), message.payload.value, cancel) + .await) + }, + }; + // The single terminal answer is how a peer learns its cancel + // was heard, so a `Cancel` wins over a refusal and over + // whatever the handler returned. + match (self.release_request(&request_id), outcome) { + (true, _) => encode_cancelled_response(), + (false, Ok(value)) => value, + (false, Err(refusal)) => { + send_protocol_error(transport.as_ref(), request_id, refusal); return; - } - } else { - let value = - (entry.handler)(request_id.clone(), message.payload.value, cancel) - .await; - // The single terminal `Response` is how a peer learns its - // cancel was heard, so it wins over whatever the handler - // returned. - if self.release_request(&request_id) { - encode_cancelled_response() - } else { - value - } + }, } }, }; From 26dc498696190e51d6c5c83a248376ee1c59c0e6 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:54:54 +0200 Subject: [PATCH 08/20] test(truapi): drop a comment that restates the test request types --- rust/crates/truapi/src/dispatcher.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index 6f0d696ff0..95904c6e03 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -557,9 +557,6 @@ mod tests { use super::*; use crate::frame::{MESSAGE_TYPE_RECEIVE, MESSAGE_TYPE_REQUEST}; use std::sync::Mutex; - // Handlers take real request types: `HostInfoRequest` and - // `HostThemeSubscribeRequest` have one fieldless version, and - // `HostLocalStorageReadRequest` two. use truapi::{ v02, versioned::{ From 3e79392697bc03328c368d485855eec6bdf6c161 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:56:10 +0200 Subject: [PATCH 09/20] docs(truapi): reword the UnsupportedVersion protocol error docs --- rust/crates/truapi/src/frame.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/rust/crates/truapi/src/frame.rs b/rust/crates/truapi/src/frame.rs index ef43678585..1015ad6744 100644 --- a/rust/crates/truapi/src/frame.rs +++ b/rust/crates/truapi/src/frame.rs @@ -77,17 +77,15 @@ pub enum ProtocolErrorV1 { /// Method discriminant of the unsupported incoming frame. method_id: u8, }, - /// The receiver handles the method but not the version the request was - /// sent in. It rejected the request before handling it, so the sender can - /// send it again in a version the receiver accepts. + /// The host knows the method but not the version of the request, and + /// rejected it without running it. #[codec(index = 1)] UnsupportedVersion { /// Trait discriminant of the rejected request. trait_id: u8, /// Method discriminant of the rejected request. method_id: u8, - /// Newest request version the receiver accepts for this method, - /// numbered like the `V` variant that carries it. + /// The newest version the host accepts for this method: `2` means `V2`. newest_version: u8, }, } From b3b108b184b7129baf98545bee3605040ffa7676 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:56:55 +0200 Subject: [PATCH 10/20] docs(truapi): reword the malformed frame error encoder's docs --- rust/crates/truapi/src/frame.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/rust/crates/truapi/src/frame.rs b/rust/crates/truapi/src/frame.rs index 1015ad6744..3c33b8c168 100644 --- a/rust/crates/truapi/src/frame.rs +++ b/rust/crates/truapi/src/frame.rs @@ -145,13 +145,11 @@ pub fn encode_cancelled_response() -> Vec { Err::<(), CallError<()>>(CallError::Cancelled).encode() } -/// Encode `Err(CallError::MalformedFrame { reason })` for a payload that did -/// not decode. +/// Encodes the answer to a payload that did not decode, as +/// `Err(CallError::MalformedFrame { reason })`. /// -/// Valid as any request's `Response` and any subscription's `Interrupt` -/// without knowing the method's types, for the same reason as -/// [`encode_cancelled_response`]: both legs are a `Result` whose `Ok` arm is -/// never reached, and `MalformedFrame` carries only its reason. +/// The bytes do not depend on the method's types, so they work as any +/// request's response and any subscription's interrupt. pub fn encode_malformed_frame_error(reason: String) -> Vec { Err::<(), CallError<()>>(CallError::MalformedFrame { reason }).encode() } From 9c62a77e94fd206b1a34f12f1963d7c1690772e3 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 14:58:36 +0200 Subject: [PATCH 11/20] docs(truapi): reword the strict decoding note on protocol errors --- rust/crates/truapi/src/protocol_error.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/rust/crates/truapi/src/protocol_error.rs b/rust/crates/truapi/src/protocol_error.rs index cc1d2329f1..fcad9efa77 100644 --- a/rust/crates/truapi/src/protocol_error.rs +++ b/rust/crates/truapi/src/protocol_error.rs @@ -15,9 +15,7 @@ use crate::frame::{ProtocolErrorV1, VersionedProtocolError}; /// frozen at whatever shape shipped first. A caller that gets `None` should /// settle the correlated call as an unspecified protocol failure and carry on. /// -/// A payload this build does recognise stays strict: a truncated or over-long -/// `V1(UnsupportedMessage)` or `V1(UnsupportedVersion)` is corruption, not a -/// newer peer, and still fails. +/// A known error that is truncated or has extra bytes is rejected as corrupt. pub fn decode_protocol_error_payload( payload: &[u8], ) -> Result, CodecError> { From 1d350f6b7b3262dd547f0fe3c7303e0935f9b6ba Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 15:15:48 +0200 Subject: [PATCH 12/20] refactor(truapi): read every known protocol error version and variant from the type --- rust/crates/truapi/src/frame.rs | 2 +- rust/crates/truapi/src/protocol_error.rs | 103 +++++++++++++++++------ 2 files changed, 80 insertions(+), 25 deletions(-) diff --git a/rust/crates/truapi/src/frame.rs b/rust/crates/truapi/src/frame.rs index 3c33b8c168..3402c69fd6 100644 --- a/rust/crates/truapi/src/frame.rs +++ b/rust/crates/truapi/src/frame.rs @@ -57,7 +57,7 @@ pub const PROTOCOL_ERROR_METHOD_ID: u8 = 255; pub const PROTOCOL_ERROR_KEY: (u8, u8) = (PROTOCOL_ERROR_TRAIT_ID, PROTOCOL_ERROR_METHOD_ID); /// Versioned payload carried by [`PROTOCOL_ERROR_KEY`] frames. -#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)] pub enum VersionedProtocolError { /// Initial protocol error shape. #[codec(index = 0)] diff --git a/rust/crates/truapi/src/protocol_error.rs b/rust/crates/truapi/src/protocol_error.rs index fcad9efa77..c0c5d6a7fc 100644 --- a/rust/crates/truapi/src/protocol_error.rs +++ b/rust/crates/truapi/src/protocol_error.rs @@ -1,9 +1,9 @@ //! Tolerant decoding of the protocol-error frame payload. use parity_scale_codec::{Decode, Error as CodecError}; -use scale_info::{TypeDef, TypeInfo}; +use scale_info::{PortableRegistry, Registry, TypeDef, TypeInfo, meta_type}; -use crate::frame::{ProtocolErrorV1, VersionedProtocolError}; +use crate::frame::VersionedProtocolError; /// Decode a [`crate::frame::PROTOCOL_ERROR_KEY`] frame's payload. /// @@ -19,29 +19,84 @@ use crate::frame::{ProtocolErrorV1, VersionedProtocolError}; pub fn decode_protocol_error_payload( payload: &[u8], ) -> Result, CodecError> { - match (payload.first(), payload.get(1)) { - (None, _) => Err("protocol error payload is empty".into()), - // A version from a later protocol. - (Some(version), _) if *version != 0 => Ok(None), - // A `V1` variant from a later protocol. - (Some(_), Some(variant)) if !is_known_v1_variant(*variant) => Ok(None), - // A `V1` variant this build knows. - _ => { - let mut input = payload; - let error = VersionedProtocolError::decode(&mut input)?; - if !input.is_empty() { - return Err("protocol error payload has trailing bytes".into()); - } - Ok(Some(error)) - }, + if payload.is_empty() { + return Err("protocol error payload is empty".into()); } + if !names_known_variants::(payload) { + return Ok(None); + } + let mut input = payload; + let error = VersionedProtocolError::decode(&mut input)?; + if !input.is_empty() { + return Err("protocol error payload has trailing bytes".into()); + } + Ok(Some(error)) +} + +/// Whether the variant indexes leading `payload` all name variants of `T`: the +/// version, then the error within that version, and so on while a variant +/// wraps a single enum. Read from `T`'s type information, so a version or an +/// error is known as soon as it is declared. +fn names_known_variants(payload: &[u8]) -> bool { + let mut registry = Registry::new(); + let mut type_id = registry.register_type(&meta_type::()).id; + let registry = PortableRegistry::from(registry); + for &index in payload { + let Some(TypeDef::Variant(def)) = registry.resolve(type_id).map(|ty| &ty.type_def) else { + return true; + }; + let Some(variant) = def.variants.iter().find(|variant| variant.index == index) else { + return false; + }; + // A variant that wraps one value puts that value's index next; any + // other variant starts its fields. + match variant.fields.as_slice() { + [field] if field.name.is_none() => type_id = field.ty.id, + _ => return true, + } + } + true } -/// Whether `index` encodes a [`ProtocolErrorV1`] variant this build knows, read -/// from the enum itself so a new variant is known the moment it is declared. -fn is_known_v1_variant(index: u8) -> bool { - matches!( - ProtocolErrorV1::type_info().type_def, - TypeDef::Variant(def) if def.variants.iter().any(|variant| variant.index == index) - ) +#[cfg(test)] +mod tests { + use parity_scale_codec::Encode; + + use super::*; + + /// A later version of the protocol error needs no change to the decoder: + /// its errors are read from the type like V1's. + #[test] + fn the_errors_of_every_version_are_read_from_the_type() { + #[derive(Encode, TypeInfo)] + enum Versioned { + V1(First), + V2(Second), + } + #[derive(Encode, TypeInfo)] + enum First { + Only { id: u8 }, + } + #[derive(Encode, TypeInfo)] + enum Second { + Only { id: u8 }, + Added { id: u8, version: u8 }, + } + + let payloads = [ + Versioned::V1(First::Only { id: 7 }).encode(), + Versioned::V2(Second::Only { id: 7 }).encode(), + Versioned::V2(Second::Added { id: 7, version: 2 }).encode(), + // An error V1 does not have. + vec![0, 1, 7], + // An error V2 does not have. + vec![1, 2, 7], + // A version that does not exist. + vec![2, 0, 7], + ]; + assert_eq!( + payloads.map(|payload| names_known_variants::(&payload)), + [true, true, true, false, false, false], + ); + } } From 7f8e42e6f0f93ee2c996cd6cb15be8dc4c1a9a69 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 15:18:30 +0200 Subject: [PATCH 13/20] refactor(truapi): check protocol error indexes one level at a time --- rust/crates/truapi/src/protocol_error.rs | 39 ++++++++++++------------ 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/rust/crates/truapi/src/protocol_error.rs b/rust/crates/truapi/src/protocol_error.rs index c0c5d6a7fc..c352dadb24 100644 --- a/rust/crates/truapi/src/protocol_error.rs +++ b/rust/crates/truapi/src/protocol_error.rs @@ -33,29 +33,28 @@ pub fn decode_protocol_error_payload( Ok(Some(error)) } -/// Whether the variant indexes leading `payload` all name variants of `T`: the -/// version, then the error within that version, and so on while a variant -/// wraps a single enum. Read from `T`'s type information, so a version or an -/// error is known as soon as it is declared. +/// Whether `T` has the version and error that `payload` starts with. fn names_known_variants(payload: &[u8]) -> bool { let mut registry = Registry::new(); - let mut type_id = registry.register_type(&meta_type::()).id; - let registry = PortableRegistry::from(registry); - for &index in payload { - let Some(TypeDef::Variant(def)) = registry.resolve(type_id).map(|ty| &ty.type_def) else { - return true; - }; - let Some(variant) = def.variants.iter().find(|variant| variant.index == index) else { - return false; - }; - // A variant that wraps one value puts that value's index next; any - // other variant starts its fields. - match variant.fields.as_slice() { - [field] if field.name.is_none() => type_id = field.ty.id, - _ => return true, - } + let type_id = registry.register_type(&meta_type::()).id; + indexes_are_known(&PortableRegistry::from(registry), type_id, payload) +} + +/// Whether `payload`'s first byte names a variant of the enum `type_id`, and, +/// when that variant wraps one value, whether the rest names that value's. +fn indexes_are_known(registry: &PortableRegistry, type_id: u32, payload: &[u8]) -> bool { + match (payload.split_first(), registry.resolve(type_id).map(|ty| &ty.type_def)) { + (Some((&index, rest)), Some(TypeDef::Variant(def))) => def + .variants + .iter() + .find(|variant| variant.index == index) + .is_some_and(|variant| match variant.fields.as_slice() { + [field] if field.name.is_none() => indexes_are_known(registry, field.ty.id, rest), + _ => true, + }), + // The payload ended, or fields follow: decoding checks the rest. + _ => true, } - true } #[cfg(test)] From 647af19c93db01967c2f964743c337301a49278e Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 15:38:46 +0200 Subject: [PATCH 14/20] docs: reword the request versions note in the README --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8ba2f2f334..c2730d88d1 100644 --- a/README.md +++ b/README.md @@ -778,8 +778,8 @@ use a different state directory while debugging. - **v0.2**: See [`docs/design/releases/v0.2.md`](docs/design/releases/v0.2.md) for the rationale behind each change. - **v0.3**: current protocol version. -A host refuses a request in a version newer than it knows, and the call -settles as unsupported. See +If a product sends a request in a newer version than the host knows, the +call fails with `Unsupported`. See [Request versions](docs/design/truapi-protocol.md#request-versions). ## Deploy From 959cab175383f79b27d222be0304adb5dbd67fa2 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 16:02:20 +0200 Subject: [PATCH 15/20] refactor(truapi): let the codec decide which protocol errors the client knows --- js/packages/truapi/src/client.test.ts | 45 ++++++++++++++++----------- js/packages/truapi/src/client.ts | 40 +++++++++--------------- js/packages/truapi/src/scale.ts | 10 +++++- 3 files changed, 49 insertions(+), 46 deletions(-) diff --git a/js/packages/truapi/src/client.test.ts b/js/packages/truapi/src/client.test.ts index 42a9cc30f3..37803c74b3 100644 --- a/js/packages/truapi/src/client.test.ts +++ b/js/packages/truapi/src/client.test.ts @@ -598,28 +598,35 @@ describe("generated client transport", () => { // report anything new without killing the connection, freezing the // channel at whatever shape shipped first. An unknown variant settles // the correlated call and leaves the transport usable. - const fixture = providerFixture(); - const transport = createTransport(fixture.provider); + for (const payload of [ + // A version this build does not know, with a payload whose length + // it cannot know either. + new Uint8Array([7, 0xaa, 0xbb]), + // A `V1` error this build does not know. + new Uint8Array([0, 9, 0xaa]), + ]) { + const fixture = providerFixture(); + const transport = createTransport(fixture.provider); - const first = transport.request>({ - ids: { trait: 200, method: 194, kind: "request" }, - payload: new Uint8Array(), - decodeResponse: () => ({ success: true, value: undefined }), - }); - // Variant 7 with a payload whose length this build cannot know. - fixture.receive(protocolError("p:1", new Uint8Array([7, 0xaa, 0xbb]))); + const first = transport.request>({ + ids: { trait: 200, method: 194, kind: "request" }, + payload: new Uint8Array(), + decodeResponse: () => ({ success: true, value: undefined }), + }); + fixture.receive(protocolError("p:1", payload)); - expect((await first)._unsafeUnwrapErr()).toEqual({ tag: "Unsupported" }); + expect((await first)._unsafeUnwrapErr()).toEqual({ tag: "Unsupported" }); - // The transport is still alive: a second call goes out and completes. - const second = transport.request>({ - ids: W.LOCAL_STORAGE_READ, - payload: new Uint8Array(), - decodeResponse: () => ({ success: true, value: undefined }), - }); - expect(fixture.sent).toHaveLength(2); - fixture.receive(wireFrame("p:2", W.LOCAL_STORAGE_READ, MESSAGE_TYPE_RESPONSE)); - expect((await second)._unsafeUnwrap()).toBeUndefined(); + // The transport is still alive: a second call goes out and completes. + const second = transport.request>({ + ids: W.LOCAL_STORAGE_READ, + payload: new Uint8Array(), + decodeResponse: () => ({ success: true, value: undefined }), + }); + expect(fixture.sent).toHaveLength(2); + fixture.receive(wireFrame("p:2", W.LOCAL_STORAGE_READ, MESSAGE_TYPE_RESPONSE)); + expect((await second)._unsafeUnwrap()).toBeUndefined(); + } }); it("rejects an unknown host-initiated message without starting an error loop", () => { diff --git a/js/packages/truapi/src/client.ts b/js/packages/truapi/src/client.ts index 872aad5cb9..90683a5aed 100644 --- a/js/packages/truapi/src/client.ts +++ b/js/packages/truapi/src/client.ts @@ -170,33 +170,26 @@ function pairKey(traitId: number, methodId: number): string { return `${traitId}:${methodId}`; } -/** - * The `V1` protocol errors this build knows, each with its SCALE index, as - * Rust's `ProtocolErrorV1` declares them. - */ -const PROTOCOL_ERRORS_V1 = { - UnsupportedMessage: [0, S.Struct({ traitId: S.u8, methodId: S.u8 })], - UnsupportedVersion: [ - 1, - S.Struct({ traitId: S.u8, methodId: S.u8, newestVersion: S.u8 }), - ], -} as const; - /** * `VersionedProtocolError`, the payload on the reserved `(255, 255)` address, - * followed by whatever bytes it leaves unread. + * as Rust declares it, followed by whatever bytes it leaves unread. */ const PROTOCOL_ERROR = S.Tuple( S.indexedTaggedUnion({ - V1: [0, S.indexedTaggedUnion(PROTOCOL_ERRORS_V1)], + V1: [ + 0, + S.indexedTaggedUnion({ + UnsupportedMessage: [0, S.Struct({ traitId: S.u8, methodId: S.u8 })], + UnsupportedVersion: [ + 1, + S.Struct({ traitId: S.u8, methodId: S.u8, newestVersion: S.u8 }), + ], + }), + ], }), S.Bytes(Infinity), ); -const KNOWN_PROTOCOL_ERRORS_V1 = new Set( - Object.values(PROTOCOL_ERRORS_V1).map(([index]) => index), -); - /** * Decode a protocol error from the reserved `(255, 255)` address. * `UnsupportedMessage` and `UnsupportedVersion` both mean the peer cannot @@ -218,18 +211,13 @@ function decodeProtocolError( if (payload.length === 0) { throw new Error("Malformed protocol error payload: empty"); } - if ( - payload[0] !== 0 || - (payload.length > 1 && !KNOWN_PROTOCOL_ERRORS_V1.has(payload[1])) - ) { - // A version or variant from a later protocol. Its length is unknowable - // here, so the remaining bytes are not validated. - return undefined; - } let decoded: ReturnType; try { decoded = PROTOCOL_ERROR.dec(payload); } catch (cause) { + // A version or error this build does not know comes from a newer peer. + // Its length is unknowable here, so the remaining bytes are not validated. + if (cause instanceof S.UnknownDiscriminantError) return undefined; throw new Error("Malformed protocol error payload: truncated", { cause }); } const [error, unread] = decoded; diff --git a/js/packages/truapi/src/scale.ts b/js/packages/truapi/src/scale.ts index e137a9a8df..d8c60f2b60 100644 --- a/js/packages/truapi/src/scale.ts +++ b/js/packages/truapi/src/scale.ts @@ -231,6 +231,14 @@ type IndexedVariantValue< : { tag: K; value: T } : never; +/** Thrown when a tagged union's encoded index names none of its variants. */ +export class UnknownDiscriminantError extends Error { + constructor(index: number) { + super(`Unknown enum discriminant: ${index}`); + this.name = "UnknownDiscriminantError"; + } +} + /** * Builds a tagged union codec with explicit SCALE discriminants. * @@ -279,7 +287,7 @@ export function indexedTaggedUnion< const index = u8.dec(input); const variant = byIndex.get(index); if (!variant) { - throw new Error(`Unknown enum discriminant: ${index}`); + throw new UnknownDiscriminantError(index); } const [tag, codec] = variant; return { tag, value: codec.dec(input) } as Output; From 8875ff2c1e7b5fa65b2b81cb976b5c9664460727 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 16:28:34 +0200 Subject: [PATCH 16/20] fix(truapi): address review of the unsupported version refusal --- js/packages/truapi/src/client.test.ts | 8 +- js/packages/truapi/src/client.ts | 30 +++++--- .../truapi-codegen/src/rust/dispatcher.rs | 2 +- rust/crates/truapi/src/dispatcher.rs | 75 +++++++++++-------- rust/crates/truapi/src/protocol_error.rs | 18 +++-- rust/crates/truapi/src/subscription.rs | 6 ++ rust/crates/truapi/src/versioned.rs | 8 +- 7 files changed, 94 insertions(+), 53 deletions(-) diff --git a/js/packages/truapi/src/client.test.ts b/js/packages/truapi/src/client.test.ts index 37803c74b3..ca688754d7 100644 --- a/js/packages/truapi/src/client.test.ts +++ b/js/packages/truapi/src/client.test.ts @@ -431,10 +431,10 @@ describe("generated client transport", () => { // Nothing is sent again after a refusal. expect(fixture.sent).toHaveLength(2); // The newest version is how a developer tells an older app from a - // corrupt request. - expect(String(warnings[0]?.[0])).toContain( - "refused request p:1 for (200, 194): it accepts versions up to V1", - ); + // corrupt request. The refusal that matched no call stays quiet. + expect(warnings.map((args) => String(args[0]))).toEqual([ + "[truapi] the host refused request p:1 for (200, 194): it accepts versions up to V1", + ]); }); it("does not settle a request from an unmatched or mismatched protocol error", async () => { diff --git a/js/packages/truapi/src/client.ts b/js/packages/truapi/src/client.ts index 90683a5aed..6d48c4908f 100644 --- a/js/packages/truapi/src/client.ts +++ b/js/packages/truapi/src/client.ts @@ -227,6 +227,25 @@ function decodeProtocolError( return error.value.value; } +/** + * Tell a developer the host refused a call's version. The call fails as + * unsupported either way; the newest version shows whether the app is older + * than the product or the request was corrupt. + */ +function reportRefusedVersion( + requestId: string, + { + traitId, + methodId, + newestVersion, + }: { traitId: number; methodId: number; newestVersion?: number }, +): void { + if (newestVersion === undefined) return; + console.warn( + `[truapi] the host refused request ${requestId} for (${traitId}, ${methodId}): it accepts versions up to V${newestVersion}`, + ); +} + /** * Build a `TrUApiTransport` on top of a `WireProvider`, adding request/response * correlation and subscription start/receive/stop lifecycle handling. @@ -410,15 +429,6 @@ export function createTransport( return; } - if (unsupported.newestVersion !== undefined) { - // The call settles as unsupported either way. The version tells a - // developer whether the app is older than the product or the request - // was corrupt. - console.warn( - `[truapi] the host refused request ${requestId} for (${unsupported.traitId}, ${unsupported.methodId}): it accepts versions up to V${unsupported.newestVersion}`, - ); - } - // Match on the whole pair: a bare method id would alias across traits and // could resolve the wrong pending call. const request = pending.get(requestId); @@ -426,6 +436,7 @@ export function createTransport( request?.ids.trait === unsupported.traitId && request?.ids.method === unsupported.methodId ) { + reportRefusedVersion(requestId, unsupported); takePending(requestId)?.resolveUnsupported(); return; } @@ -435,6 +446,7 @@ export function createTransport( subscription?.ids.trait === unsupported.traitId && subscription?.ids.method === unsupported.methodId ) { + reportRefusedVersion(requestId, unsupported); subscriptions.delete(requestId); subscription.onClose?.( new UnsupportedMessageError( diff --git a/rust/crates/truapi-codegen/src/rust/dispatcher.rs b/rust/crates/truapi-codegen/src/rust/dispatcher.rs index 5d8cf9947c..bf7bd6ebab 100644 --- a/rust/crates/truapi-codegen/src/rust/dispatcher.rs +++ b/rust/crates/truapi-codegen/src/rust/dispatcher.rs @@ -4,7 +4,7 @@ //! For each method the emitter produces an `on_request` (or //! `on_subscription`) registration whose handler: //! 1. Receives the versioned request wrapper, which the framework has decoded from the wire bytes -//! (the wrapper's own variant tag carries its version — there is no outer envelope). The +//! (the wrapper's own variant tag carries its version, and there is no outer envelope). The //! framework refuses a version newer than the wrapper's `Versioned::LATEST`, and answers bytes //! that do not decode with `MalformedFrame`, before the handler runs. //! 2. Calls the host trait method (which receives the wrapper directly and matches `_::V1(inner)` diff --git a/rust/crates/truapi/src/dispatcher.rs b/rust/crates/truapi/src/dispatcher.rs index 95904c6e03..54122ccfb5 100644 --- a/rust/crates/truapi/src/dispatcher.rs +++ b/rust/crates/truapi/src/dispatcher.rs @@ -14,7 +14,7 @@ use std::{ use futures::future::{self, BoxFuture}; use parity_scale_codec::{Decode, DecodeAll, Encode}; -use tracing::{debug, error, instrument}; +use tracing::{error, instrument}; use truapi::{CancellationToken, versioned::Versioned}; use crate::{ @@ -66,34 +66,6 @@ pub struct SubscriptionEntry { handler: SubscriptionHandler, } -/// Returns the error to send back when `payload` is in a version newer than -/// `newest_version`. The first byte of a request is its version, starting at -/// 0 for `V1`. -fn unsupported_version( - ids: MethodIds, - newest_version: u8, - payload: &[u8], -) -> Option { - let index = *payload.first()?; - if index < newest_version { - return None; - } - // The first byte is all a refusal reads, so a corrupt payload is refused - // too. An implausible version here tells the two apart. - debug!( - trait_id = ids.trait_id, - method_id = ids.method_id, - version = u16::from(index) + 1, - newest_version, - "refusing a request in a version this host does not know" - ); - Some(VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { - trait_id: ids.trait_id, - method_id: ids.method_id, - newest_version, - })) -} - /// Answer `request_id` on the reserved protocol-error address. fn send_protocol_error( transport: &dyn Transport, @@ -234,6 +206,37 @@ impl Dispatcher { } } + /// Returns the error to send back when `payload` is in a version newer than + /// `newest_version`. The first byte of a request is its version, starting + /// at 0 for `V1`. + fn unsupported_version( + &self, + ids: MethodIds, + newest_version: u8, + payload: &[u8], + ) -> Option { + let index = *payload.first()?; + if index < newest_version { + return None; + } + // The first byte is all a refusal reads, so a corrupt payload is + // refused too. An implausible version tells the two apart. + self.report_once((ids.trait_id, ids.method_id), || { + error!( + trait_id = ids.trait_id, + method_id = ids.method_id, + version = u16::from(index) + 1, + newest_version, + "refusing a request in a version this host does not know" + ); + }); + Some(VersionedProtocolError::V1(ProtocolErrorV1::UnsupportedVersion { + trait_id: ids.trait_id, + method_id: ids.method_id, + newest_version, + })) + } + /// Return whether this connection may access a service execution kind. pub fn allows_execution(&self, required: crate::platform::ProductExecutionKind) -> bool { self.execution.is_none_or(|actual| actual == required) @@ -368,7 +371,7 @@ impl Dispatcher { }, Reservation::AlreadyWithdrawn => encode_cancelled_response(), Reservation::Start(cancel) => { - let outcome = match unsupported_version( + let outcome = match self.unsupported_version( entry.ids, entry.newest_version, &message.payload.value, @@ -430,7 +433,7 @@ impl Dispatcher { // Refused the way a `Start` that fails to decode is: the reservation // has already replaced any live subscription under this id. if let Some(error) = - unsupported_version(entry.ids, entry.newest_version, &message.payload.value) + self.unsupported_version(entry.ids, entry.newest_version, &message.payload.value) { self.subscriptions.cancel_reservation(token); send_protocol_error(transport.as_ref(), request_id, error); @@ -652,7 +655,7 @@ mod tests { let dispatcher = Dispatcher::new(test_spawner()); let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); - let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()); + let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, Vec::new()); futures::executor::block_on(dispatcher.dispatch(frame, transport_dyn)); // 250 != 251 on purpose: the reply must echo the pair in the order it // arrived, and equal values would let a transposition pass. @@ -773,6 +776,11 @@ mod tests { ] ); assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1); + assert_eq!( + *dispatcher.reported_violations.lock().expect("violation set"), + HashSet::from([(7, 200)]), + "a refusal is logged for its method, like any wire disagreement" + ); } /// The dispatcher decodes a request before its handler sees it, so bytes @@ -840,6 +848,7 @@ mod tests { }] ); assert!(!invoked.load(std::sync::atomic::Ordering::SeqCst)); + assert!(!dispatcher.subscriptions.holds("p:1"), "a refused start keeps no slot"); } /// A refusal is an answer like any other, so a `Cancel` that arrived first @@ -1420,7 +1429,7 @@ mod tests { let transport = Arc::new(RecordingTransport::default()); let transport_dyn: Arc = transport.clone(); for _ in 0..3 { - let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, HostInfoRequest::V1.encode()); + let frame = make_frame(250, 251, MESSAGE_TYPE_REQUEST, Vec::new()); futures::executor::block_on(dispatcher.dispatch(frame, transport_dyn.clone())); } assert_eq!( diff --git a/rust/crates/truapi/src/protocol_error.rs b/rust/crates/truapi/src/protocol_error.rs index c352dadb24..591b7d7a3d 100644 --- a/rust/crates/truapi/src/protocol_error.rs +++ b/rust/crates/truapi/src/protocol_error.rs @@ -1,5 +1,7 @@ //! Tolerant decoding of the protocol-error frame payload. +use std::sync::LazyLock; + use parity_scale_codec::{Decode, Error as CodecError}; use scale_info::{PortableRegistry, Registry, TypeDef, TypeInfo, meta_type}; @@ -22,7 +24,8 @@ pub fn decode_protocol_error_payload( if payload.is_empty() { return Err("protocol error payload is empty".into()); } - if !names_known_variants::(payload) { + let (registry, type_id) = &*PROTOCOL_ERROR_TYPES; + if !indexes_are_known(registry, *type_id, payload) { return Ok(None); } let mut input = payload; @@ -33,11 +36,15 @@ pub fn decode_protocol_error_payload( Ok(Some(error)) } -/// Whether `T` has the version and error that `payload` starts with. -fn names_known_variants(payload: &[u8]) -> bool { +/// [`VersionedProtocolError`]'s type information, built on first use. +static PROTOCOL_ERROR_TYPES: LazyLock<(PortableRegistry, u32)> = + LazyLock::new(type_registry::); + +/// `T`'s type information, and the id `T` is registered under. +fn type_registry() -> (PortableRegistry, u32) { let mut registry = Registry::new(); let type_id = registry.register_type(&meta_type::()).id; - indexes_are_known(&PortableRegistry::from(registry), type_id, payload) + (registry.into(), type_id) } /// Whether `payload`'s first byte names a variant of the enum `type_id`, and, @@ -93,8 +100,9 @@ mod tests { // A version that does not exist. vec![2, 0, 7], ]; + let (registry, type_id) = type_registry::(); assert_eq!( - payloads.map(|payload| names_known_variants::(&payload)), + payloads.map(|payload| indexes_are_known(®istry, type_id, &payload)), [true, true, true, false, false, false], ); } diff --git a/rust/crates/truapi/src/subscription.rs b/rust/crates/truapi/src/subscription.rs index 7e3a6cc82f..0101c99a02 100644 --- a/rust/crates/truapi/src/subscription.rs +++ b/rust/crates/truapi/src/subscription.rs @@ -158,6 +158,12 @@ impl SubscriptionManager { ReservationToken { request_id, generation } } + /// Whether `request_id` holds a slot, reserved or live. + #[cfg(test)] + pub fn holds(&self, request_id: &str) -> bool { + self.active.lock().unwrap().contains_key(request_id) + } + /// Drop a reservation whose `_start` handler failed before producing a /// stream. No-op if the slot was superseded by a newer reservation. pub fn cancel_reservation(&self, token: ReservationToken) { diff --git a/rust/crates/truapi/src/versioned.rs b/rust/crates/truapi/src/versioned.rs index 101c877d7b..b02187c45f 100644 --- a/rust/crates/truapi/src/versioned.rs +++ b/rust/crates/truapi/src/versioned.rs @@ -11,6 +11,11 @@ //! encoded inside any of these payloads. /// A versioned message envelope. +/// +/// Its encoding starts with `version() - 1`, and versions run from 1 to +/// [`LATEST`](Self::LATEST) with no gaps. The dispatcher reads that first byte +/// to refuse a request newer than its handler knows. `versioned_type!` keeps +/// this; a hand-written impl must too. pub trait Versioned: Sized { /// The newest version's payload. Handlers operate exclusively on this. type Latest; @@ -82,7 +87,8 @@ mod tests { } // Multi-version envelopes assign positional SCALE codec indices (V1 -> 0, - // V2 -> 1) and 1-based version numbers. + // V2 -> 1) and 1-based version numbers. The dispatcher reads that first + // byte to refuse a request newer than its handler knows. #[test] fn multi_version_codec_indices_are_positional() { use super::Versioned; From d8da55c6c2c2b5556d19d860c28635093c6290bf Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 16:32:47 +0200 Subject: [PATCH 17/20] test(truapi): reword the unknown protocol error payload comments --- js/packages/truapi/src/client.test.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/js/packages/truapi/src/client.test.ts b/js/packages/truapi/src/client.test.ts index ca688754d7..9a356c90d0 100644 --- a/js/packages/truapi/src/client.test.ts +++ b/js/packages/truapi/src/client.test.ts @@ -599,10 +599,9 @@ describe("generated client transport", () => { // channel at whatever shape shipped first. An unknown variant settles // the correlated call and leaves the transport usable. for (const payload of [ - // A version this build does not know, with a payload whose length - // it cannot know either. + // An unknown version (byte 7), followed by bytes this build can't read. new Uint8Array([7, 0xaa, 0xbb]), - // A `V1` error this build does not know. + // A known version (V1) with an unknown error (byte 9). new Uint8Array([0, 9, 0xaa]), ]) { const fixture = providerFixture(); From 2e251f5838b58fdb47a089e2c8a7c3105adb0844 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 16:36:04 +0200 Subject: [PATCH 18/20] docs(truapi): reword the unknown protocol error comment in the client --- js/packages/truapi/src/client.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/js/packages/truapi/src/client.ts b/js/packages/truapi/src/client.ts index 6d48c4908f..711d8faaea 100644 --- a/js/packages/truapi/src/client.ts +++ b/js/packages/truapi/src/client.ts @@ -215,8 +215,8 @@ function decodeProtocolError( try { decoded = PROTOCOL_ERROR.dec(payload); } catch (cause) { - // A version or error this build does not know comes from a newer peer. - // Its length is unknowable here, so the remaining bytes are not validated. + // An unknown version or error means a newer peer. We don't know its + // layout, so we don't check the rest. if (cause instanceof S.UnknownDiscriminantError) return undefined; throw new Error("Malformed protocol error payload: truncated", { cause }); } From d5cafd022d71f60498fb00c73abe0dbe90cd491e Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 16:36:49 +0200 Subject: [PATCH 19/20] docs(truapi): shorten the refused version warning's doc comment --- js/packages/truapi/src/client.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/js/packages/truapi/src/client.ts b/js/packages/truapi/src/client.ts index 711d8faaea..35f74de35e 100644 --- a/js/packages/truapi/src/client.ts +++ b/js/packages/truapi/src/client.ts @@ -227,11 +227,7 @@ function decodeProtocolError( return error.value.value; } -/** - * Tell a developer the host refused a call's version. The call fails as - * unsupported either way; the newest version shows whether the app is older - * than the product or the request was corrupt. - */ +/** Warns that the host refused a call's version, naming the newest it accepts. */ function reportRefusedVersion( requestId: string, { From f0de99c4827c5ddb82e0a8f1bdb6adedcc2fbce2 Mon Sep 17 00:00:00 2001 From: Mikelle Date: Thu, 22 Oct 2026 16:48:46 +0200 Subject: [PATCH 20/20] docs(truapi): reword the Versioned encoding rule --- rust/crates/truapi/src/versioned.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/rust/crates/truapi/src/versioned.rs b/rust/crates/truapi/src/versioned.rs index b02187c45f..470e910487 100644 --- a/rust/crates/truapi/src/versioned.rs +++ b/rust/crates/truapi/src/versioned.rs @@ -12,10 +12,9 @@ /// A versioned message envelope. /// -/// Its encoding starts with `version() - 1`, and versions run from 1 to -/// [`LATEST`](Self::LATEST) with no gaps. The dispatcher reads that first byte -/// to refuse a request newer than its handler knows. `versioned_type!` keeps -/// this; a hand-written impl must too. +/// The first encoded byte is `version() - 1`, and every version from 1 to +/// [`LATEST`](Self::LATEST) exists. The dispatcher relies on this to refuse a +/// request in a newer version. pub trait Versioned: Sized { /// The newest version's payload. Handlers operate exclusively on this. type Latest;