|
| 1 | +import { |
| 2 | + hasProperty, |
| 3 | + isJsonRpcRequest, |
| 4 | + isObject, |
| 5 | + JsonRpcId, |
| 6 | + JsonRpcNotification, |
| 7 | + JsonRpcRequest, |
| 8 | + JsonRpcResponse, |
| 9 | + RuntimeObject, |
| 10 | +} from '@metamask/utils'; |
| 11 | +import { Duplex } from 'readable-stream'; |
| 12 | +import { |
| 13 | + DuplexJsonRpcEngine, |
| 14 | + JsonRpcMiddleware, |
| 15 | + JsonRpcNotificationHandler, |
| 16 | +} from 'json-rpc-engine'; |
| 17 | +import { ErrorMessages, IdMapValue } from './utils'; |
| 18 | + |
| 19 | +type StreamCallback = (error?: Error | null) => void; |
| 20 | + |
| 21 | +interface DuplexJsonRpcStreamOptions { |
| 22 | + receiverMiddleware?: JsonRpcMiddleware<unknown, unknown>[]; |
| 23 | + receiverNotificationHandler?: JsonRpcNotificationHandler<unknown>; |
| 24 | + senderMiddleware?: JsonRpcMiddleware<unknown, unknown>[]; |
| 25 | + senderNotificationHandler?: JsonRpcNotificationHandler<unknown>; |
| 26 | +} |
| 27 | + |
| 28 | +/** |
| 29 | + * Foobar, bar baz. |
| 30 | + * |
| 31 | + * @param options - Options bag. |
| 32 | + * @returns The stream wrapping the duplex JSON-RPC engine. |
| 33 | + */ |
| 34 | +export default function createDuplexJsonRpcStream( |
| 35 | + options: DuplexJsonRpcStreamOptions, |
| 36 | +) { |
| 37 | + const { |
| 38 | + receiverMiddleware = [], |
| 39 | + receiverNotificationHandler = () => undefined, |
| 40 | + senderMiddleware = [], |
| 41 | + senderNotificationHandler, |
| 42 | + } = options; |
| 43 | + |
| 44 | + const outgoingIdMap: Map<JsonRpcId, IdMapValue> = new Map(); |
| 45 | + const stream = new Duplex({ |
| 46 | + objectMode: true, |
| 47 | + read: () => undefined, |
| 48 | + write: processMessage, |
| 49 | + }); |
| 50 | + |
| 51 | + const sendNotification = (notification: JsonRpcNotification<unknown>) => { |
| 52 | + stream.push(notification); |
| 53 | + return undefined; |
| 54 | + }; |
| 55 | + |
| 56 | + const _senderNotificationHandler = senderNotificationHandler |
| 57 | + ? async (notification: JsonRpcNotification<unknown>) => { |
| 58 | + await senderNotificationHandler(notification); |
| 59 | + return sendNotification(notification); |
| 60 | + } |
| 61 | + : sendNotification; |
| 62 | + |
| 63 | + const engine = new DuplexJsonRpcEngine({ |
| 64 | + receiverNotificationHandler, |
| 65 | + senderNotificationHandler: _senderNotificationHandler, |
| 66 | + }); |
| 67 | + |
| 68 | + receiverMiddleware.forEach((middleware) => |
| 69 | + engine.addReceiverMiddleware(middleware), |
| 70 | + ); |
| 71 | + |
| 72 | + senderMiddleware.forEach((middleware) => |
| 73 | + engine.addSenderMiddleware(middleware), |
| 74 | + ); |
| 75 | + |
| 76 | + engine.addSenderMiddleware((req, res, _next, end) => { |
| 77 | + // write req to stream |
| 78 | + stream.push(req); |
| 79 | + // register request on id map if |
| 80 | + if (isJsonRpcRequest(req)) { |
| 81 | + outgoingIdMap.set(req.id, { res, end }); |
| 82 | + } |
| 83 | + }); |
| 84 | + |
| 85 | + return { duplexEngine: engine, duplexEngineStream: stream }; |
| 86 | + |
| 87 | + /** |
| 88 | + * Writes a JSON-RPC object to the stream. |
| 89 | + * |
| 90 | + * @param message - The message to write to the stream. |
| 91 | + * @param _encoding - The stream encoding, not used. |
| 92 | + * @param cb - The stream write callback. |
| 93 | + * @returns Nothing. |
| 94 | + */ |
| 95 | + function processMessage( |
| 96 | + message: unknown, |
| 97 | + _encoding: unknown, |
| 98 | + cb: StreamCallback, |
| 99 | + ): void { |
| 100 | + let err: Error | null = null; |
| 101 | + try { |
| 102 | + if (!isObject(message)) { |
| 103 | + throw new Error('not an object'); |
| 104 | + } else if (isResponse(message)) { |
| 105 | + receiveResponse(message); |
| 106 | + } else if (isRequest(message)) { |
| 107 | + return receiveRequest(message, cb); |
| 108 | + } else { |
| 109 | + throw new Error('neither a response nor request'); |
| 110 | + } |
| 111 | + } catch (_err) { |
| 112 | + err = _err as Error; |
| 113 | + } |
| 114 | + |
| 115 | + // continue processing stream |
| 116 | + return cb(err); |
| 117 | + } |
| 118 | + |
| 119 | + /** |
| 120 | + * Forwards a JSON-RPC request or notification to the receiving pipeline. |
| 121 | + * Pushes any response from the pipeline to the stream. |
| 122 | + * |
| 123 | + * @param req - The request or notification to receive. |
| 124 | + * @param cb - The stream write callback. |
| 125 | + */ |
| 126 | + function receiveRequest( |
| 127 | + req: JsonRpcRequest<unknown> | JsonRpcNotification<unknown>, |
| 128 | + cb: StreamCallback, |
| 129 | + ) { |
| 130 | + // TypeScript defaults to the notification overload and we don't get a |
| 131 | + // response unless we cast. |
| 132 | + engine |
| 133 | + .receive(req as JsonRpcRequest<unknown>) |
| 134 | + .then((response) => { |
| 135 | + if (response) { |
| 136 | + stream.push(response); |
| 137 | + } |
| 138 | + cb(); |
| 139 | + }) |
| 140 | + .catch((error) => cb(error)); |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Receives a response to a request sent via the sending pipeline. |
| 145 | + * |
| 146 | + * @param res - The response to receive. |
| 147 | + */ |
| 148 | + function receiveResponse(res: JsonRpcResponse<unknown>) { |
| 149 | + const context = outgoingIdMap.get(res.id); |
| 150 | + if (!context) { |
| 151 | + throw new Error(ErrorMessages.unknownResponse(res.id)); |
| 152 | + } |
| 153 | + |
| 154 | + // Copy response received from the stream unto original response object, |
| 155 | + // which will be returned by the engine on this side. |
| 156 | + Object.assign(context.res, res); |
| 157 | + |
| 158 | + outgoingIdMap.delete(res.id); |
| 159 | + // Prevent internal stream handler from catching errors from this callback. |
| 160 | + setTimeout(context.end); |
| 161 | + } |
| 162 | +} |
| 163 | + |
| 164 | +/** |
| 165 | + * A type guard for {@link JsonRpcResponse}. |
| 166 | + * |
| 167 | + * @param message - The object to type check. |
| 168 | + * @returns The type check result. |
| 169 | + */ |
| 170 | +function isResponse( |
| 171 | + message: RuntimeObject, |
| 172 | +): message is JsonRpcResponse<unknown> { |
| 173 | + return hasProperty(message, 'result') || hasProperty(message, 'error'); |
| 174 | +} |
| 175 | + |
| 176 | +/** |
| 177 | + * A type guard for {@link JsonRpcRequest} or {@link JsonRpcNotification}. |
| 178 | + * |
| 179 | + * @param message - The object to type check. |
| 180 | + * @returns The type check result. |
| 181 | + */ |
| 182 | +function isRequest( |
| 183 | + message: RuntimeObject, |
| 184 | +): message is JsonRpcRequest<unknown> | JsonRpcNotification<unknown> { |
| 185 | + return hasProperty(message, 'method'); |
| 186 | +} |
0 commit comments