@onekeyfe/hd-transport 1.2.0-alpha.2 → 1.2.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/__tests__/messages.test.js +122 -0
- package/__tests__/protocol-v2-link-manager.test.js +326 -0
- package/__tests__/protocol-v2-usb-transport-base.test.js +296 -0
- package/__tests__/protocol-v2.test.js +371 -107
- package/dist/constants.d.ts +5 -3
- package/dist/constants.d.ts.map +1 -1
- package/dist/index.d.ts +912 -371
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +551 -254
- package/dist/protocols/index.d.ts +10 -5
- package/dist/protocols/index.d.ts.map +1 -1
- package/dist/protocols/v2/constants.d.ts +1 -0
- package/dist/protocols/v2/constants.d.ts.map +1 -1
- package/dist/protocols/v2/decode.d.ts +2 -2
- package/dist/protocols/v2/decode.d.ts.map +1 -1
- package/dist/protocols/v2/encode.d.ts +2 -3
- package/dist/protocols/v2/encode.d.ts.map +1 -1
- package/dist/protocols/v2/index.d.ts +0 -1
- package/dist/protocols/v2/index.d.ts.map +1 -1
- package/dist/protocols/v2/link-manager.d.ts +35 -0
- package/dist/protocols/v2/link-manager.d.ts.map +1 -0
- package/dist/protocols/v2/sequence-cursor.d.ts +5 -0
- package/dist/protocols/v2/sequence-cursor.d.ts.map +1 -0
- package/dist/protocols/v2/session.d.ts +15 -4
- package/dist/protocols/v2/session.d.ts.map +1 -1
- package/dist/protocols/v2/usb-transport-base.d.ts +31 -0
- package/dist/protocols/v2/usb-transport-base.d.ts.map +1 -0
- package/dist/serialization/protobuf/decode.d.ts.map +1 -1
- package/dist/serialization/protobuf/messages.d.ts.map +1 -1
- package/dist/types/messages.d.ts +535 -226
- package/dist/types/messages.d.ts.map +1 -1
- package/dist/types/transport.d.ts +5 -3
- package/dist/types/transport.d.ts.map +1 -1
- package/messages-protocol-v2.json +825 -709
- package/package.json +3 -3
- package/scripts/protobuf-build.sh +96 -310
- package/scripts/protobuf-patches/index.js +1 -0
- package/scripts/protobuf-types.js +12 -0
- package/src/constants.ts +21 -15
- package/src/index.ts +8 -0
- package/src/protocols/index.ts +31 -40
- package/src/protocols/v2/constants.ts +1 -0
- package/src/protocols/v2/crc8.ts +1 -1
- package/src/protocols/v2/decode.ts +31 -34
- package/src/protocols/v2/encode.ts +2 -28
- package/src/protocols/v2/index.ts +0 -1
- package/src/protocols/v2/link-manager.ts +160 -0
- package/src/protocols/v2/sequence-cursor.ts +10 -0
- package/src/protocols/v2/session.ts +79 -180
- package/src/protocols/v2/usb-transport-base.ts +194 -0
- package/src/serialization/protobuf/decode.ts +4 -1
- package/src/serialization/protobuf/messages.ts +6 -1
- package/src/types/messages.ts +637 -266
- package/src/types/transport.ts +3 -3
- package/dist/protocols/v2/debug.d.ts +0 -13
- package/dist/protocols/v2/debug.d.ts.map +0 -1
- package/src/protocols/v2/debug.ts +0 -26
package/src/protocols/index.ts
CHANGED
|
@@ -6,10 +6,9 @@ import { decodeMessage as decodeV1Message } from './v1/receive';
|
|
|
6
6
|
import { createMessageFromName, createMessageFromType } from '../serialization/protobuf/messages';
|
|
7
7
|
import { encode as encodeProtobuf } from '../serialization/protobuf/encode';
|
|
8
8
|
import { decode as decodeProtobuf } from '../serialization/protobuf/decode';
|
|
9
|
-
import { decodeFrame as decodeV2Frame, encodeProtobufFrame } from './v2';
|
|
9
|
+
import { decodeFrame as decodeV2Frame, encodeProtobufFrame, isAckFrame } from './v2';
|
|
10
10
|
|
|
11
11
|
import type { Root } from 'protobufjs/light';
|
|
12
|
-
import type { ProtocolV2DebugLogger } from './v2';
|
|
13
12
|
|
|
14
13
|
export const PROTOCOL_V2_SYS_MESSAGE_THRESHOLD = 60000;
|
|
15
14
|
|
|
@@ -23,9 +22,6 @@ type ProtocolV2FrameOptions = {
|
|
|
23
22
|
router?: number;
|
|
24
23
|
/** Sequence number (1-255). Managed per-session by ProtocolV2Session. */
|
|
25
24
|
seq?: number;
|
|
26
|
-
logger?: ProtocolV2DebugLogger;
|
|
27
|
-
logPrefix?: string;
|
|
28
|
-
context?: string;
|
|
29
25
|
};
|
|
30
26
|
|
|
31
27
|
const resolveProtocolV2EncodeSchema = (name: string, schemas: ProtocolV2Schemas) => {
|
|
@@ -38,6 +34,7 @@ const resolveProtocolV2EncodeSchema = (name: string, schemas: ProtocolV2Schemas)
|
|
|
38
34
|
};
|
|
39
35
|
|
|
40
36
|
const PROTOCOL_V2_LEGACY_DECODE_ALLOWLIST = new Set([
|
|
37
|
+
'Failure',
|
|
41
38
|
'ButtonRequest',
|
|
42
39
|
'EntropyRequest',
|
|
43
40
|
'PinMatrixRequest',
|
|
@@ -73,6 +70,20 @@ export const ProtocolV1 = {
|
|
|
73
70
|
};
|
|
74
71
|
|
|
75
72
|
export const ProtocolV2 = {
|
|
73
|
+
isAckFrame,
|
|
74
|
+
|
|
75
|
+
inspectFrame(schemas: ProtocolV2Schemas, frame: Uint8Array) {
|
|
76
|
+
const { messageTypeId, pbPayload, seq } = decodeV2Frame(frame);
|
|
77
|
+
const { messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
|
|
78
|
+
return {
|
|
79
|
+
messageName,
|
|
80
|
+
messageTypeId,
|
|
81
|
+
pbPayload,
|
|
82
|
+
seq,
|
|
83
|
+
type: messageName,
|
|
84
|
+
};
|
|
85
|
+
},
|
|
86
|
+
|
|
76
87
|
encodeFrame(
|
|
77
88
|
schemas: ProtocolV2Schemas,
|
|
78
89
|
name: string,
|
|
@@ -86,51 +97,31 @@ export const ProtocolV2 = {
|
|
|
86
97
|
const rawPbBuffer = pbBuffer.toBuffer() as unknown as ArrayBuffer;
|
|
87
98
|
const pbBytes = new Uint8Array(rawPbBuffer);
|
|
88
99
|
|
|
89
|
-
options.logger?.debug?.(`[${options.logPrefix ?? 'ProtocolV2'}] encode protobuf`, {
|
|
90
|
-
context: options.context ?? `encode:${name}`,
|
|
91
|
-
messageName: name,
|
|
92
|
-
messageTypeId,
|
|
93
|
-
pbPayloadLength: pbBytes.length,
|
|
94
|
-
packetSrc: options.packetSrc ?? 0,
|
|
95
|
-
router: options.router ?? 0,
|
|
96
|
-
});
|
|
97
|
-
|
|
98
100
|
return encodeProtobufFrame(
|
|
99
101
|
messageTypeId,
|
|
100
102
|
pbBytes,
|
|
101
103
|
options.packetSrc,
|
|
102
104
|
options.router,
|
|
103
|
-
{
|
|
104
|
-
logger: options.logger,
|
|
105
|
-
logPrefix: options.logPrefix,
|
|
106
|
-
context: options.context ?? `encode:${name}`,
|
|
107
|
-
messageName: name,
|
|
108
|
-
},
|
|
109
105
|
options.seq
|
|
110
106
|
);
|
|
111
107
|
},
|
|
112
108
|
|
|
113
|
-
decodeFrame(
|
|
114
|
-
schemas
|
|
115
|
-
|
|
116
|
-
options: Pick<ProtocolV2FrameOptions, 'logger' | 'logPrefix' | 'context'> = {}
|
|
117
|
-
) {
|
|
118
|
-
const { messageTypeId, pbPayload, seq } = decodeV2Frame(frame, {
|
|
119
|
-
logger: options.logger,
|
|
120
|
-
logPrefix: options.logPrefix,
|
|
121
|
-
context: options.context ?? 'decode',
|
|
122
|
-
});
|
|
123
|
-
const { Message, messageName } = createProtocolV2MessageFromType(messageTypeId, schemas);
|
|
109
|
+
decodeFrame(schemas: ProtocolV2Schemas, frame: Uint8Array) {
|
|
110
|
+
const { messageTypeId, pbPayload, seq, messageName } = this.inspectFrame(schemas, frame);
|
|
111
|
+
const { Message } = createProtocolV2MessageFromType(messageTypeId, schemas);
|
|
124
112
|
const rxByteBuffer = ByteBuffer.wrap(Buffer.from(pbPayload) as unknown as ArrayBuffer);
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
113
|
+
let message: ReturnType<typeof decodeProtobuf>;
|
|
114
|
+
try {
|
|
115
|
+
message = decodeProtobuf(Message, rxByteBuffer);
|
|
116
|
+
} catch (cause) {
|
|
117
|
+
const error = new Error(
|
|
118
|
+
`Protocol V2 protobuf decode failed for "${messageName}" ` +
|
|
119
|
+
`(${messageTypeId}, ${pbPayload.length}-byte payload); ` +
|
|
120
|
+
'the payload is malformed or incompatible with the active SDK schema.'
|
|
121
|
+
);
|
|
122
|
+
(error as Error & { cause?: unknown }).cause = cause;
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
134
125
|
|
|
135
126
|
return {
|
|
136
127
|
message,
|
package/src/protocols/v2/crc8.ts
CHANGED
|
@@ -22,7 +22,7 @@ export const CRC8_TABLE = new Uint8Array([
|
|
|
22
22
|
]);
|
|
23
23
|
|
|
24
24
|
/**
|
|
25
|
-
*
|
|
25
|
+
* Compute CRC-8 over the first len bytes using the firmware-compatible initial value.
|
|
26
26
|
*/
|
|
27
27
|
export function crc8(data: Uint8Array, len: number): number {
|
|
28
28
|
let crc = CRC8_INIT;
|
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import { PROTO_HEAD_CRC_SIZE, PROTO_HEAD_SOF } from './constants';
|
|
1
|
+
import { PROTO_DATA_TYPE_ACK, PROTO_HEAD_CRC_SIZE, PROTO_HEAD_SOF } from './constants';
|
|
2
2
|
import { crc8 } from './crc8';
|
|
3
|
-
import { logProtocolV2Debug } from './debug';
|
|
4
|
-
|
|
5
|
-
import type { ProtocolV2FrameDebugOptions } from './debug';
|
|
6
3
|
|
|
7
4
|
export interface ProtoV2Frame {
|
|
8
5
|
/** Little-endian message type ID */
|
|
@@ -13,20 +10,7 @@ export interface ProtoV2Frame {
|
|
|
13
10
|
seq: number;
|
|
14
11
|
}
|
|
15
12
|
|
|
16
|
-
|
|
17
|
-
* Parse and validate a Protocol V2 response frame.
|
|
18
|
-
*
|
|
19
|
-
* Validates:
|
|
20
|
-
* - SOF byte (0x5A)
|
|
21
|
-
* - Header CRC (bytes 0-2)
|
|
22
|
-
* - Frame CRC (full frame except last byte)
|
|
23
|
-
*
|
|
24
|
-
* Returns the decoded messageTypeId, raw protobuf payload, and sequence number.
|
|
25
|
-
*/
|
|
26
|
-
export function decodeFrame(
|
|
27
|
-
data: Uint8Array,
|
|
28
|
-
debugOptions?: ProtocolV2FrameDebugOptions
|
|
29
|
-
): ProtoV2Frame {
|
|
13
|
+
function validateFrame(data: Uint8Array): number {
|
|
30
14
|
if (data.length < PROTO_HEAD_CRC_SIZE) {
|
|
31
15
|
throw new Error(`Protocol V2 frame too short: ${data.length} bytes`);
|
|
32
16
|
}
|
|
@@ -43,7 +27,6 @@ export function decodeFrame(
|
|
|
43
27
|
throw new Error(`Frame truncated: expected ${frameLen} bytes, got ${data.length}`);
|
|
44
28
|
}
|
|
45
29
|
|
|
46
|
-
// Verify pre-header CRC (bytes 0-2)
|
|
47
30
|
const expectedHeaderCrc = crc8(data, 3);
|
|
48
31
|
if (data[3] !== expectedHeaderCrc) {
|
|
49
32
|
throw new Error(
|
|
@@ -53,7 +36,6 @@ export function decodeFrame(
|
|
|
53
36
|
);
|
|
54
37
|
}
|
|
55
38
|
|
|
56
|
-
// Verify frame CRC (all bytes except last)
|
|
57
39
|
const expectedFrameCrc = crc8(data, frameLen - 1);
|
|
58
40
|
if (data[frameLen - 1] !== expectedFrameCrc) {
|
|
59
41
|
throw new Error(
|
|
@@ -63,6 +45,35 @@ export function decodeFrame(
|
|
|
63
45
|
);
|
|
64
46
|
}
|
|
65
47
|
|
|
48
|
+
return frameLen;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function isAckFrame(data: Uint8Array): boolean {
|
|
52
|
+
// eslint-disable-next-line no-bitwise
|
|
53
|
+
if (data.length < 6 || (data[5] & 0x03) !== PROTO_DATA_TYPE_ACK) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const frameLen = validateFrame(data);
|
|
58
|
+
if (frameLen !== PROTO_HEAD_CRC_SIZE) {
|
|
59
|
+
throw new Error(`Invalid Protocol V2 ACK frame length: ${frameLen}`);
|
|
60
|
+
}
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Parse and validate a Protocol V2 response frame.
|
|
66
|
+
*
|
|
67
|
+
* Validates:
|
|
68
|
+
* - SOF byte (0x5A)
|
|
69
|
+
* - Header CRC (bytes 0-2)
|
|
70
|
+
* - Frame CRC (full frame except last byte)
|
|
71
|
+
*
|
|
72
|
+
* Returns the decoded messageTypeId, raw protobuf payload, and sequence number.
|
|
73
|
+
*/
|
|
74
|
+
export function decodeFrame(data: Uint8Array): ProtoV2Frame {
|
|
75
|
+
const frameLen = validateFrame(data);
|
|
76
|
+
|
|
66
77
|
const seq = data[6];
|
|
67
78
|
// Payload spans bytes 7 to frameLen-2 (inclusive), excluding final CRC byte
|
|
68
79
|
const payloadData = data.slice(7, frameLen - 1);
|
|
@@ -74,19 +85,5 @@ export function decodeFrame(
|
|
|
74
85
|
const messageTypeId = payloadData[0] + payloadData[1] * 256;
|
|
75
86
|
const pbPayload = payloadData.slice(2);
|
|
76
87
|
|
|
77
|
-
logProtocolV2Debug(debugOptions, 'decode raw frame', {
|
|
78
|
-
frameLen,
|
|
79
|
-
dataLength: data.length,
|
|
80
|
-
router: data[4],
|
|
81
|
-
attr: data[5],
|
|
82
|
-
seq,
|
|
83
|
-
headerCrc: data[3],
|
|
84
|
-
expectedHeaderCrc,
|
|
85
|
-
frameCrc: data[frameLen - 1],
|
|
86
|
-
expectedFrameCrc,
|
|
87
|
-
messageTypeId,
|
|
88
|
-
pbPayloadLength: pbPayload.length,
|
|
89
|
-
});
|
|
90
|
-
|
|
91
88
|
return { messageTypeId, pbPayload, seq };
|
|
92
89
|
}
|
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { PROTO_DATA_TYPE_PACKET, PROTO_HEAD_CRC_SIZE, PROTO_HEAD_SOF } from './constants';
|
|
2
2
|
import { crc8 } from './crc8';
|
|
3
|
-
import { logProtocolV2Debug } from './debug';
|
|
4
3
|
import { PROTOCOL_V2_FRAME_MAX_BYTES } from '../../constants';
|
|
5
4
|
|
|
6
|
-
import type { ProtocolV2FrameDebugOptions } from './debug';
|
|
7
|
-
|
|
8
5
|
// Default sequence number when callers do not manage one themselves.
|
|
9
6
|
// Stateful per-session sequencing lives in ProtocolV2Session (session.ts),
|
|
10
7
|
// which advances the counter via nextProtoSeq() and passes it in explicitly.
|
|
@@ -35,7 +32,6 @@ export function encodeFrame(
|
|
|
35
32
|
payload: Uint8Array | null,
|
|
36
33
|
packetSrc?: number,
|
|
37
34
|
router?: number,
|
|
38
|
-
debugOptions?: ProtocolV2FrameDebugOptions,
|
|
39
35
|
seq?: number
|
|
40
36
|
): Uint8Array {
|
|
41
37
|
const resolvedPacketSrc = packetSrc ?? 0;
|
|
@@ -47,7 +43,7 @@ export function encodeFrame(
|
|
|
47
43
|
const payloadLen = payload ? payload.length : 0;
|
|
48
44
|
const frameLen = payloadLen + PROTO_HEAD_CRC_SIZE;
|
|
49
45
|
if (frameLen > PROTOCOL_V2_FRAME_MAX_BYTES) {
|
|
50
|
-
throw new Error(`Protocol V2 frame too large: ${frameLen}`);
|
|
46
|
+
throw new Error(`Protocol V2 frame too large: ${frameLen} > ${PROTOCOL_V2_FRAME_MAX_BYTES}`);
|
|
51
47
|
}
|
|
52
48
|
const frame = new Uint8Array(frameLen);
|
|
53
49
|
|
|
@@ -69,17 +65,6 @@ export function encodeFrame(
|
|
|
69
65
|
// CRC8 over entire frame except last byte
|
|
70
66
|
frame[frameLen - 1] = crc8(frame, frameLen - 1);
|
|
71
67
|
|
|
72
|
-
logProtocolV2Debug(debugOptions, 'encode raw frame', {
|
|
73
|
-
frameLen,
|
|
74
|
-
payloadLen,
|
|
75
|
-
packetSrc: resolvedPacketSrc,
|
|
76
|
-
router: frame[4],
|
|
77
|
-
attr: frame[5],
|
|
78
|
-
seq: frame[6],
|
|
79
|
-
headerCrc: frame[3],
|
|
80
|
-
frameCrc: frame[frameLen - 1],
|
|
81
|
-
});
|
|
82
|
-
|
|
83
68
|
return frame;
|
|
84
69
|
}
|
|
85
70
|
|
|
@@ -95,22 +80,11 @@ export function encodeProtobufFrame(
|
|
|
95
80
|
pbPayload: Uint8Array,
|
|
96
81
|
packetSrc?: number,
|
|
97
82
|
router?: number,
|
|
98
|
-
debugOptions?: ProtocolV2FrameDebugOptions,
|
|
99
83
|
seq?: number
|
|
100
84
|
): Uint8Array {
|
|
101
85
|
const payload = new Uint8Array(2 + pbPayload.length);
|
|
102
86
|
payload[0] = messageTypeId % 256;
|
|
103
87
|
payload[1] = Math.floor(messageTypeId / 256) % 256;
|
|
104
88
|
payload.set(pbPayload, 2);
|
|
105
|
-
return encodeFrame(
|
|
106
|
-
payload,
|
|
107
|
-
packetSrc,
|
|
108
|
-
router,
|
|
109
|
-
{
|
|
110
|
-
...debugOptions,
|
|
111
|
-
messageTypeId,
|
|
112
|
-
pbPayloadLength: pbPayload.length,
|
|
113
|
-
},
|
|
114
|
-
seq
|
|
115
|
-
);
|
|
89
|
+
return encodeFrame(payload, packetSrc, router, seq);
|
|
116
90
|
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { ProtocolV2SequenceCursor } from './sequence-cursor';
|
|
2
|
+
import { ProtocolV2Session, getErrorMessage } from './session';
|
|
3
|
+
|
|
4
|
+
import type { MessageFromOneKey, TransportCallOptions } from '../../types';
|
|
5
|
+
import type { ProtocolV2CallContext, ProtocolV2Schemas, ProtocolV2SessionOptions } from './session';
|
|
6
|
+
|
|
7
|
+
export type ProtocolV2LinkErrorClassification = 'link-fatal' | 'recoverable';
|
|
8
|
+
|
|
9
|
+
export interface ProtocolV2LinkAdapter {
|
|
10
|
+
router: number;
|
|
11
|
+
maxFrameBytes?: number;
|
|
12
|
+
generation: number;
|
|
13
|
+
prepareCall(context: ProtocolV2CallContext): Promise<void> | void;
|
|
14
|
+
writeFrame(frame: Uint8Array, context: ProtocolV2CallContext): Promise<void>;
|
|
15
|
+
readFrame(context: ProtocolV2CallContext): Promise<Uint8Array>;
|
|
16
|
+
reset(reason: string): Promise<void> | void;
|
|
17
|
+
logger?: ProtocolV2SessionOptions['logger'];
|
|
18
|
+
logPrefix?: string;
|
|
19
|
+
createTimeoutError?: ProtocolV2SessionOptions['createTimeoutError'];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type ProtocolV2LinkManagerOptions<Key> = {
|
|
23
|
+
getSchemas: () => ProtocolV2Schemas;
|
|
24
|
+
classifyError: (error: unknown) => ProtocolV2LinkErrorClassification;
|
|
25
|
+
onLinkInvalidated?: (key: Key, reason: string) => Promise<void> | void;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
type ProtocolV2Link = {
|
|
29
|
+
adapter: ProtocolV2LinkAdapter;
|
|
30
|
+
session: ProtocolV2Session;
|
|
31
|
+
state: {
|
|
32
|
+
invalidatedReason?: string;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export class ProtocolV2LinkManager<Key> {
|
|
37
|
+
private readonly links = new Map<Key, ProtocolV2Link>();
|
|
38
|
+
|
|
39
|
+
private readonly sequences = new Map<Key, ProtocolV2SequenceCursor>();
|
|
40
|
+
|
|
41
|
+
private readonly callQueues = new Map<Key, Promise<unknown>>();
|
|
42
|
+
|
|
43
|
+
private readonly options: ProtocolV2LinkManagerOptions<Key>;
|
|
44
|
+
|
|
45
|
+
constructor(options: ProtocolV2LinkManagerOptions<Key>) {
|
|
46
|
+
this.options = options;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
call(
|
|
50
|
+
key: Key,
|
|
51
|
+
createAdapter: () => ProtocolV2LinkAdapter,
|
|
52
|
+
name: string,
|
|
53
|
+
data: Record<string, unknown>,
|
|
54
|
+
options?: TransportCallOptions
|
|
55
|
+
): Promise<MessageFromOneKey> {
|
|
56
|
+
const run = () => this.executeCall(key, createAdapter, name, data, options);
|
|
57
|
+
const previous = this.callQueues.get(key) ?? Promise.resolve();
|
|
58
|
+
const result = previous.then(run, run);
|
|
59
|
+
const queue = result.catch(() => undefined);
|
|
60
|
+
this.callQueues.set(key, queue);
|
|
61
|
+
result
|
|
62
|
+
.then(
|
|
63
|
+
() => this.clearSettledCallQueue(key, queue),
|
|
64
|
+
() => this.clearSettledCallQueue(key, queue)
|
|
65
|
+
)
|
|
66
|
+
.catch(() => undefined);
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async invalidateLink(key: Key, reason: string): Promise<void> {
|
|
71
|
+
const link = this.links.get(key);
|
|
72
|
+
if (!link) return;
|
|
73
|
+
|
|
74
|
+
this.links.delete(key);
|
|
75
|
+
link.state.invalidatedReason = reason;
|
|
76
|
+
await link.adapter.reset(reason);
|
|
77
|
+
await this.options.onLinkInvalidated?.(key, reason);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async invalidateAllLinks(reason: string): Promise<void> {
|
|
81
|
+
await Promise.all(Array.from(this.links.keys(), key => this.invalidateLink(key, reason)));
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async dispose(reason: string): Promise<void> {
|
|
85
|
+
await this.invalidateAllLinks(reason);
|
|
86
|
+
this.sequences.clear();
|
|
87
|
+
this.callQueues.clear();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
private getOrCreateLink(key: Key, createAdapter: () => ProtocolV2LinkAdapter): ProtocolV2Link {
|
|
91
|
+
const existing = this.links.get(key);
|
|
92
|
+
if (existing) return existing;
|
|
93
|
+
|
|
94
|
+
const adapter = createAdapter();
|
|
95
|
+
const state: ProtocolV2Link['state'] = {};
|
|
96
|
+
const assertLinkActive = () => {
|
|
97
|
+
if (state.invalidatedReason) {
|
|
98
|
+
throw new Error(state.invalidatedReason);
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
let sequenceCursor = this.sequences.get(key);
|
|
102
|
+
if (!sequenceCursor) {
|
|
103
|
+
sequenceCursor = new ProtocolV2SequenceCursor();
|
|
104
|
+
this.sequences.set(key, sequenceCursor);
|
|
105
|
+
}
|
|
106
|
+
const session = new ProtocolV2Session({
|
|
107
|
+
schemas: this.options.getSchemas(),
|
|
108
|
+
router: adapter.router,
|
|
109
|
+
maxFrameBytes: adapter.maxFrameBytes,
|
|
110
|
+
generation: adapter.generation,
|
|
111
|
+
sequenceCursor,
|
|
112
|
+
prepareCall: async context => {
|
|
113
|
+
assertLinkActive();
|
|
114
|
+
await adapter.prepareCall(context);
|
|
115
|
+
assertLinkActive();
|
|
116
|
+
},
|
|
117
|
+
writeFrame: async (frame, context) => {
|
|
118
|
+
assertLinkActive();
|
|
119
|
+
await adapter.writeFrame(frame, context);
|
|
120
|
+
assertLinkActive();
|
|
121
|
+
},
|
|
122
|
+
readFrame: async context => {
|
|
123
|
+
assertLinkActive();
|
|
124
|
+
const frame = await adapter.readFrame(context);
|
|
125
|
+
assertLinkActive();
|
|
126
|
+
return frame;
|
|
127
|
+
},
|
|
128
|
+
logger: adapter.logger,
|
|
129
|
+
logPrefix: adapter.logPrefix,
|
|
130
|
+
createTimeoutError: adapter.createTimeoutError,
|
|
131
|
+
});
|
|
132
|
+
const link = { adapter, session, state };
|
|
133
|
+
this.links.set(key, link);
|
|
134
|
+
return link;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async executeCall(
|
|
138
|
+
key: Key,
|
|
139
|
+
createAdapter: () => ProtocolV2LinkAdapter,
|
|
140
|
+
name: string,
|
|
141
|
+
data: Record<string, unknown>,
|
|
142
|
+
options?: TransportCallOptions
|
|
143
|
+
): Promise<MessageFromOneKey> {
|
|
144
|
+
try {
|
|
145
|
+
return await this.getOrCreateLink(key, createAdapter).session.call(name, data, options);
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (this.options.classifyError(error) === 'link-fatal') {
|
|
148
|
+
const errorMessage = getErrorMessage(error) || 'unknown error';
|
|
149
|
+
await this.invalidateLink(key, `Protocol V2 link-fatal error: ${errorMessage}`);
|
|
150
|
+
}
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
private clearSettledCallQueue(key: Key, queue: Promise<unknown>) {
|
|
156
|
+
if (this.callQueues.get(key) === queue) {
|
|
157
|
+
this.callQueues.delete(key);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|