Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
db0b05d
feat(truapi): refuse a request in a version the host does not know
Mikelle Oct 22, 2026
5a87148
docs(changeset): reword the request versions release note
Mikelle Oct 22, 2026
17419e5
docs(truapi): reword the unsupported version note in the README
Mikelle Oct 22, 2026
4a3b108
docs(truapi): reword the unsupported version helper's doc comment
Mikelle Oct 22, 2026
e30b202
refactor(truapi): name the dispatcher's decoding wrapper apart from t…
Mikelle Oct 22, 2026
28332f7
fix(truapi): let a Cancel that beats a version refusal answer Cancelled
Mikelle Oct 22, 2026
ba960d5
refactor(truapi): settle a reserved call's answer in one match
Mikelle Oct 22, 2026
26dc498
test(truapi): drop a comment that restates the test request types
Mikelle Oct 22, 2026
3e79392
docs(truapi): reword the UnsupportedVersion protocol error docs
Mikelle Oct 22, 2026
b3b108b
docs(truapi): reword the malformed frame error encoder's docs
Mikelle Oct 22, 2026
9c62a77
docs(truapi): reword the strict decoding note on protocol errors
Mikelle Oct 22, 2026
1d350f6
refactor(truapi): read every known protocol error version and variant…
Mikelle Oct 22, 2026
7f8e42e
refactor(truapi): check protocol error indexes one level at a time
Mikelle Oct 22, 2026
01e2160
Merge remote-tracking branch 'origin/main' into feat/request-versions
Mikelle Oct 22, 2026
647af19
docs: reword the request versions note in the README
Mikelle Oct 22, 2026
959cab1
refactor(truapi): let the codec decide which protocol errors the clie…
Mikelle Oct 22, 2026
8875ff2
fix(truapi): address review of the unsupported version refusal
Mikelle Oct 22, 2026
d8da55c
test(truapi): reword the unknown protocol error payload comments
Mikelle Oct 22, 2026
2e251f5
docs(truapi): reword the unknown protocol error comment in the client
Mikelle Oct 22, 2026
d5cafd0
docs(truapi): shorten the refused version warning's doc comment
Mikelle Oct 22, 2026
f0de99c
docs(truapi): reword the Versioned encoding rule
Mikelle Oct 22, 2026
dda046d
Merge remote-tracking branch 'origin/main' into feat/unsupported-vers…
Mikelle Oct 22, 2026
335bee4
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 23, 2026
65f9082
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 23, 2026
9eec928
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 23, 2026
f9bdf34
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 26, 2026
a88a8ca
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 26, 2026
58f1fe7
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 26, 2026
a976778
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 26, 2026
e14e635
Merge branch 'main' into feat/unsupported-version-error
Mikelle Oct 26, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/request-versions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@parity/truapi": minor
"@parity/truapi-host": minor
---

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`.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,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.

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

Pushes to `main` build and deploy:
Expand Down
20 changes: 20 additions & 0 deletions docs/design/truapi-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Comment thread
Mikelle marked this conversation as resolved.
Resolved

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`.

2 changes: 2 additions & 0 deletions js/packages/truapi/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

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

`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:
Expand Down
130 changes: 108 additions & 22 deletions js/packages/truapi/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<string, CallErrorValue<never>>({
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. 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 () => {
const fixture = providerFixture();
const transport = createTransport(fixture.provider);
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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) {
Expand All @@ -518,28 +598,34 @@ 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 [
// An unknown version (byte 7), followed by bytes this build can't read.
new Uint8Array([7, 0xaa, 0xbb]),
// A known version (V1) with an unknown error (byte 9).
new Uint8Array([0, 9, 0xaa]),
]) {
const fixture = providerFixture();
const transport = createTransport(fixture.provider);

const first = transport.request<undefined, CallErrorValue<never>>({
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<undefined, CallErrorValue<never>>({
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<undefined, CallErrorValue<never>>({
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<undefined, CallErrorValue<never>>({
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", () => {
Expand Down
77 changes: 58 additions & 19 deletions js/packages/truapi/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,29 @@ function pairKey(traitId: number, methodId: number): string {
}

/**
* Decode `V1(UnsupportedMessage { trait_id, method_id })` from the reserved
* `(255, 255)` address.
* `VersionedProtocolError`, the payload on the reserved `(255, 255)` address,
* as Rust declares it, followed by whatever bytes it leaves unread.
*/
const PROTOCOL_ERROR = S.Tuple(
S.indexedTaggedUnion({
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),
);

/**
* 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
Expand All @@ -181,28 +202,44 @@ 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)) {
// 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<typeof PROTOCOL_ERROR.dec>;
try {
decoded = PROTOCOL_ERROR.dec(payload);
} catch (cause) {
// 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 });
}
if (payload.length !== 4) {
throw new Error(
`Malformed protocol error payload: expected 4 bytes, received ${payload.length}`,
);
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;
}

/** Warns that the host refused a call's version, naming the newest it accepts. */
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}`,
);
}

/**
Expand Down Expand Up @@ -358,9 +395,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<typeof decodeProtocolError>;
try {
unsupported = decodeUnsupportedMessage(payload.value);
unsupported = decodeProtocolError(payload.value);
} catch (error) {
onProtocolError(toError(error));
return;
Expand Down Expand Up @@ -395,6 +432,7 @@ export function createTransport(
request?.ids.trait === unsupported.traitId &&
request?.ids.method === unsupported.methodId
) {
reportRefusedVersion(requestId, unsupported);
takePending(requestId)?.resolveUnsupported();
return;
}
Expand All @@ -404,6 +442,7 @@ export function createTransport(
subscription?.ids.trait === unsupported.traitId &&
subscription?.ids.method === unsupported.methodId
) {
reportRefusedVersion(requestId, unsupported);
subscriptions.delete(requestId);
subscription.onClose?.(
new UnsupportedMessageError(
Expand Down
10 changes: 9 additions & 1 deletion js/packages/truapi/src/scale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading