Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
37 changes: 15 additions & 22 deletions js/packages/truapi/src/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Result } from "neverthrow";
import { describe, expect, it } from "bun:test";

import { createTransport } from "./client.js";
import { CallError, indexedTaggedUnion, Result as ScaleResult, str, _void } from "./scale.js";
import { indexedTaggedUnion, Result as ScaleResult, str, _void } from "./scale.js";
import type { Codec } from "./scale.js";
import { createClient, SubscriptionError } from "./generated/client.js";
import * as T from "./generated/types.js";
Expand Down Expand Up @@ -60,7 +60,7 @@ function providerFixture() {

/** Encode a V1 host-handshake response result payload. */
function handshakeResponsePayload(value: { success: true; value: undefined }): Uint8Array {
return versionedV1(ScaleResult(_void, CallError(T.VersionedHostHandshakeError))).enc({
return versionedV1(ScaleResult(_void, T.HostHandshakeError)).enc({
tag: "V1",
value,
});
Expand All @@ -74,11 +74,11 @@ function accountGetResponsePayload(
}
| {
success: false;
value: { tag: "Domain"; value: T.VersionedHostAccountGetError };
value: T.HostAccountGetError;
},
): Uint8Array {
return versionedV1(
ScaleResult(T.HostAccountGetResponse, CallError(T.VersionedHostAccountGetError)),
ScaleResult(T.HostAccountGetResponse, T.HostAccountGetError),
).enc({ tag: "V1", value });
}

Expand Down Expand Up @@ -158,15 +158,15 @@ describe("generated client transport", () => {
const response = client.account.getAccount({
productAccountId: { dotNsIdentifier: "foo", derivationIndex: 0 },
});
const reason = { tag: "V1", value: { tag: "NotConnected", value: undefined } } as const;
const reason = { tag: "NotConnected", value: undefined } as const;
const frame = unwrap(
encodeWireMessage({
requestId: "p:1",
payload: {
id: W.ACCOUNT_GET_ACCOUNT.response,
value: accountGetResponsePayload({
success: false,
value: { tag: "Domain", value: reason },
value: reason,
}),
},
}),
Expand All @@ -176,7 +176,7 @@ describe("generated client transport", () => {

const result = await response;
expect(result.isErr()).toBe(true);
expect(result._unsafeUnwrapErr()).toEqual({ tag: "Domain", value: reason });
expect(result._unsafeUnwrapErr()).toEqual(reason);
});

it("auto-responds to an inbound handshake with the versioned-result shape", () => {
Expand Down Expand Up @@ -275,18 +275,14 @@ describe("generated client transport", () => {
});

const reason = { tag: "PermissionDenied", value: undefined } as const;
const callError = {
tag: "Domain",
value: { tag: "V1", value: reason },
} as const;
const frame = unwrap(
encodeWireMessage({
requestId: sub.subscriptionId,
payload: {
id: W.PAYMENT_BALANCE_SUBSCRIBE.interrupt,
value: versionedV1(CallError(T.VersionedHostPaymentBalanceSubscribeError)).enc({
value: T.VersionedHostPaymentBalanceSubscribeError.enc({
tag: "V1",
value: callError,
value: reason,
}),
},
}),
Expand All @@ -297,7 +293,7 @@ describe("generated client transport", () => {
expect(completions).toEqual([]);
expect(errors).toHaveLength(1);
expect(errors[0]).toBeInstanceOf(SubscriptionError);
expect((errors[0] as SubscriptionError).reason).toEqual(callError);
expect((errors[0] as SubscriptionError).reason).toEqual(reason);
expect(fixture.sent).toHaveLength(1);
});

Expand All @@ -312,18 +308,15 @@ describe("generated client transport", () => {
.subscribe({ error: (error) => errors.push(error) });

const reason = "Denied";
const callError = {
tag: "Domain",
value: { tag: "V1", value: reason },
} as const;
const frame = unwrap(
encodeWireMessage({
requestId: sub.subscriptionId,
payload: {
id: W.COIN_PAYMENT_REBALANCE_PURSE.interrupt,
value: versionedV1(
CallError(T.VersionedHostCoinPaymentRebalancePurseError),
).enc({ tag: "V1", value: callError }),
value: T.VersionedHostCoinPaymentRebalancePurseError.enc({
tag: "V1",
value: reason,
}),
},
}),
"encode typed coin payment interrupt",
Expand All @@ -332,7 +325,7 @@ describe("generated client transport", () => {

expect(errors).toHaveLength(1);
expect(errors[0]).toBeInstanceOf(SubscriptionError);
expect((errors[0] as SubscriptionError).reason).toEqual(callError);
expect((errors[0] as SubscriptionError).reason).toEqual(reason);
});

it("treats a malformed receive payload as terminal and sends _stop", () => {
Expand Down
19 changes: 4 additions & 15 deletions js/packages/truapi/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,9 @@ import {
type WireProvider,
} from "./transport.js";
import {
CallError,
indexedTaggedUnion,
Result,
_void,
type CallErrorValue,
type Codec,
type ResultPayload,
} from "./scale.js";
Expand Down Expand Up @@ -52,10 +50,7 @@ function protocolVersionTag(version: number): `V${number}` {
return `V${version}` as `V${number}`;
}

type HandshakeResponse = ResultPayload<
undefined,
CallErrorValue<T.VersionedHostHandshakeError>
>;
type HandshakeResponse = ResultPayload<undefined, T.HostHandshakeError>;
const HANDSHAKE_WIRE_VERSION = 1;

/**
Expand All @@ -67,7 +62,7 @@ function handshakeResponseCodec(
return indexedTaggedUnion({
[protocolVersionTag(version)]: [
version - 1,
Result(_void, CallError(T.VersionedHostHandshakeError)),
Result(_void, T.HostHandshakeError),
] as const,
}) as Codec<{ tag: `V${number}`; value: HandshakeResponse }>;
}
Expand All @@ -94,14 +89,8 @@ function encodeUnsupportedHandshakeResponse(version: number): Uint8Array {
value: {
success: false,
value: {
tag: "Domain",
value: {
tag: "V1",
value: {
tag: "UnsupportedProtocolVersion",
value: undefined,
},
},
tag: "UnsupportedProtocolVersion",
value: undefined,
},
},
});
Expand Down
21 changes: 0 additions & 21 deletions js/packages/truapi/src/scale.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,9 @@
import {
Bytes,
Enum,
Struct,
createCodec,
createDecoder,
enhanceCodec,
str,
u8,
_void,
type Codec,
Expand Down Expand Up @@ -123,25 +121,6 @@ export function TaggedUnion<O extends TaggedUnionCodecs>(
return Enum(inner) as unknown as Codec<TaggedUnionValue<O>>;
}

/** Public TS value for Rust's derived `CallError<D>` enum. */
export type CallErrorValue<D> =
| { tag: "Domain"; value: D }
| { tag: "Denied"; value?: undefined }
| { tag: "Unsupported"; value?: undefined }
| { tag: "MalformedFrame"; value: { reason: string } }
| { tag: "HostFailure"; value: { reason: string } };

/** SCALE codec for Rust's derived `CallError<D>` enum. */
export function CallError<D>(domain: Codec<D>): Codec<CallErrorValue<D>> {
return TaggedUnion({
Domain: domain,
Denied: _void,
Unsupported: _void,
MalformedFrame: Struct({ reason: str }),
HostFailure: Struct({ reason: str }),
}) as Codec<CallErrorValue<D>>;
}

type TaggedUnionCodecs = {
[Sym: symbol]: never;
[Num: number]: never;
Expand Down
27 changes: 22 additions & 5 deletions rust/crates/truapi-codegen/src/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -200,10 +200,30 @@ mod tests {
}
}

/// Domain payload enum backing a versioned test wrapper, carrying the
/// `Unknown { reason }` catch-all the error emission folds into.
fn domain_test_type(name: &str) -> TypeDef {
TypeDef {
name: format!("V01{name}"),
module_path: Vec::new(),
generic_params: Vec::new(),
kind: TypeDefKind::Enum(vec![VariantDef {
name: "Unknown".to_string(),
fields: VariantFields::Named(vec![FieldDef {
name: "reason".to_string(),
type_ref: TypeRef::Primitive("str".to_string()),
docs: None,
}]),
docs: None,
}]),
docs: None,
}
}

fn versioned_request_test_types() -> Vec<TypeDef> {
["ReqWrapper", "RespWrapper", "ErrWrapper"]
.into_iter()
.map(versioned_test_type)
.flat_map(|name| [versioned_test_type(name), domain_test_type(name)])
.collect()
}

Expand Down Expand Up @@ -672,10 +692,7 @@ mod tests {
docs: None,
}],
public_trait_order: vec!["Permissions".to_string()],
types: vec![
versioned_test_type("RespWrapper"),
versioned_test_type("ErrWrapper"),
],
types: versioned_request_test_types(),
};

let err = generate_dispatcher(&api).expect_err("missing target version must error");
Expand Down
Loading
Loading