mqtt-json-rpc 1.3.7 → 2.1.0

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.
@@ -0,0 +1,287 @@
1
+ /*
2
+ ** MQTT-JSON-RPC -- JSON-RPC protocol over MQTT communication
3
+ ** Copyright (c) 2018-2025 Dr. Ralf S. Engelschall <rse@engelschall.com>
4
+ **
5
+ ** Permission is hereby granted, free of charge, to any person obtaining
6
+ ** a copy of this software and associated documentation files (the
7
+ ** "Software"), to deal in the Software without restriction, including
8
+ ** without limitation the rights to use, copy, modify, merge, publish,
9
+ ** distribute, sublicense, and/or sell copies of the Software, and to
10
+ ** permit persons to whom the Software is furnished to do so, subject to
11
+ ** the following conditions:
12
+ **
13
+ ** The above copyright notice and this permission notice shall be included
14
+ ** in all copies or substantial portions of the Software.
15
+ **
16
+ ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ ** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ ** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ ** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ ** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ ** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ ** SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
+ */
24
+ import UUID from "pure-uuid";
25
+ import JSONRPC, { JsonRpcError } from "jsonrpc-lite";
26
+ import Encodr from "encodr";
27
+ /* the API class */
28
+ export default class API {
29
+ /* construct API class */
30
+ constructor(mqtt, options = {}) {
31
+ this.mqtt = mqtt;
32
+ this.registry = new Map();
33
+ this.requests = new Map();
34
+ this.subscriptions = new Map();
35
+ /* determine options */
36
+ this.options = {
37
+ clientId: (new UUID(1)).format("std"),
38
+ encoding: "json",
39
+ timeout: 10 * 1000,
40
+ topicRequestMake: (method) => `${method}/request`,
41
+ topicResponseMake: (method, clientId) => `${method}/response/${clientId}`,
42
+ topicRequestMatch: (topic) => topic.match(/^(.+?)\/request$/),
43
+ topicResponseMatch: (topic) => topic.match(/^(.+?)\/response\/(.+)$/),
44
+ ...options
45
+ };
46
+ /* establish an encoder */
47
+ this.encodr = new Encodr(this.options.encoding);
48
+ /* hook into the MQTT message processing */
49
+ this.mqtt.on("message", (topic, message) => {
50
+ this._onServerMessage(topic, message);
51
+ this._onClientMessage(topic, message);
52
+ });
53
+ }
54
+ /*
55
+ * RPC server/response side
56
+ */
57
+ /* check for the registration of an RPC method */
58
+ registered(method) {
59
+ return this.registry.has(method);
60
+ }
61
+ /* register an RPC method */
62
+ register(method, callback) {
63
+ if (this.registry.has(method))
64
+ throw new Error(`register: method "${method}" already registered`);
65
+ this.registry.set(method, callback);
66
+ return new Promise((resolve, reject) => {
67
+ const topic = this.options.topicRequestMake(method);
68
+ this.mqtt.subscribe(topic, { qos: 2 }, (err, granted) => {
69
+ if (err)
70
+ reject(err);
71
+ else
72
+ resolve();
73
+ });
74
+ });
75
+ }
76
+ /* unregister an RPC method */
77
+ unregister(method) {
78
+ if (!this.registry.has(method))
79
+ throw new Error(`unregister: method "${method}" not registered`);
80
+ this.registry.delete(method);
81
+ return new Promise((resolve, reject) => {
82
+ const topic = this.options.topicRequestMake(method);
83
+ this.mqtt.unsubscribe(topic, (err, packet) => {
84
+ if (err)
85
+ reject(err);
86
+ else
87
+ resolve();
88
+ });
89
+ });
90
+ }
91
+ /* handle incoming RPC method request */
92
+ _onServerMessage(topic, message) {
93
+ /* ensure we handle only MQTT JSON-RPC requests */
94
+ if (this.options.topicRequestMatch(topic) === null)
95
+ return;
96
+ /* try to parse payload as JSON-RPC payload */
97
+ let parsed;
98
+ try {
99
+ parsed = JSONRPC.parseObject(this.encodr.decode(message));
100
+ }
101
+ catch (_error) {
102
+ return;
103
+ }
104
+ if (!(typeof parsed === "object" && typeof parsed.type === "string"))
105
+ return;
106
+ /* determine method from JSON-RPC payload */
107
+ const method = parsed.payload.method;
108
+ /* dispatch according to JSON-RPC type */
109
+ if (parsed.type === "notification")
110
+ /* just deliver notification */
111
+ this.registry.get(method)?.(...parsed.payload.params);
112
+ else if (parsed.type === "request") {
113
+ /* deliver request and send response */
114
+ let response;
115
+ const handler = this.registry.get(method);
116
+ if (handler !== undefined)
117
+ response = Promise.resolve().then(() => handler(...parsed.payload.params));
118
+ else
119
+ response = Promise.reject(JsonRpcError.methodNotFound({ method, id: parsed.payload.id }));
120
+ response.then((result) => {
121
+ /* create JSON-RPC success response */
122
+ return JSONRPC.success(parsed.payload.id, result);
123
+ }, (error) => {
124
+ /* create JSON-RPC error response */
125
+ return this._buildError(parsed.payload, error);
126
+ }).then((rpcResponse) => {
127
+ /* send MQTT response message */
128
+ const idMatch = parsed.payload.id.match(/^(.+):.+$/);
129
+ if (idMatch === null)
130
+ throw new Error("invalid request id format");
131
+ const encoded = this.encodr.encode(rpcResponse);
132
+ const clientId = idMatch[1];
133
+ const topic = this.options.topicResponseMake(method, clientId);
134
+ this.mqtt.publish(topic, encoded, { qos: 0 });
135
+ }).catch((err) => {
136
+ this.mqtt.emit("error", err);
137
+ });
138
+ }
139
+ }
140
+ /*
141
+ * RPC client/request side
142
+ */
143
+ /* notify peer ("fire and forget") */
144
+ notify(method, ...params) {
145
+ const topic = this.options.topicRequestMake(method);
146
+ let request = JSONRPC.notification(method, params);
147
+ request = this.encodr.encode(request);
148
+ this.mqtt.publish(topic, request, { qos: 0 });
149
+ }
150
+ /* call peer ("request and response") */
151
+ call(method, ...params) {
152
+ /* determine unique request id */
153
+ const rid = `${this.options.clientId}:${(new UUID(1)).format("std")}`;
154
+ /* subscribe for response */
155
+ this._responseSubscribe(method);
156
+ /* create promise for response handling */
157
+ const promise = new Promise((resolve, reject) => {
158
+ let timer = setTimeout(() => {
159
+ this.requests.delete(rid);
160
+ this._responseUnsubscribe(method);
161
+ timer = null;
162
+ reject(new Error("communication timeout"));
163
+ }, this.options.timeout);
164
+ this.requests.set(rid, (err, result) => {
165
+ if (timer !== null) {
166
+ clearTimeout(timer);
167
+ timer = null;
168
+ }
169
+ if (err)
170
+ reject(err);
171
+ else
172
+ resolve(result);
173
+ });
174
+ });
175
+ let request = JSONRPC.request(rid, method, params);
176
+ /* send MQTT request message */
177
+ const topic = this.options.topicRequestMake(method);
178
+ request = this.encodr.encode(request);
179
+ this.mqtt.publish(topic, request, { qos: 2 }, (err) => {
180
+ const callback = this.requests.get(rid);
181
+ if (err && callback !== undefined) {
182
+ /* handle request failure */
183
+ this._responseUnsubscribe(method);
184
+ callback(err, undefined);
185
+ this.requests.delete(rid);
186
+ }
187
+ });
188
+ return promise;
189
+ }
190
+ /* handle incoming RPC method response */
191
+ _onClientMessage(topic, message) {
192
+ /* ensure we handle only MQTT JSON-RPC responses */
193
+ let m;
194
+ if ((m = this.options.topicResponseMatch(topic)) === null)
195
+ return;
196
+ /* ensure we really handle only MQTT RPC responses for us */
197
+ const clientId = m[2];
198
+ if (clientId !== this.options.clientId)
199
+ return;
200
+ /* try to parse payload as JSON-RPC payload */
201
+ let parsed;
202
+ try {
203
+ parsed = JSONRPC.parseObject(this.encodr.decode(message));
204
+ }
205
+ catch (_error) {
206
+ return;
207
+ }
208
+ if (!(typeof parsed === "object" && typeof parsed.type === "string"))
209
+ return;
210
+ /* determine method from JSON-RPC payload */
211
+ const method = parsed.payload.method;
212
+ /* dispatch according to JSON-RPC type */
213
+ if (parsed.type === "success" || parsed.type === "error") {
214
+ const rid = parsed.payload.id;
215
+ const callback = this.requests.get(rid);
216
+ if (callback !== undefined) {
217
+ /* call callback function */
218
+ if (parsed.type === "success")
219
+ callback(undefined, parsed.payload.result);
220
+ else
221
+ callback(parsed.payload.error, undefined);
222
+ /* unsubscribe from response */
223
+ this.requests.delete(rid);
224
+ this._responseUnsubscribe(method);
225
+ }
226
+ }
227
+ }
228
+ /* subscribe to RPC response */
229
+ _responseSubscribe(method) {
230
+ const topic = this.options.topicResponseMake(method, this.options.clientId);
231
+ if (!this.subscriptions.has(topic)) {
232
+ this.subscriptions.set(topic, 0);
233
+ this.mqtt.subscribe(topic, { qos: 2 }, (err) => {
234
+ if (err)
235
+ this.mqtt.emit("error", err);
236
+ });
237
+ }
238
+ this.subscriptions.set(topic, this.subscriptions.get(topic) + 1);
239
+ }
240
+ /* unsubscribe from RPC response */
241
+ _responseUnsubscribe(method) {
242
+ const topic = this.options.topicResponseMake(method, this.options.clientId);
243
+ if (!this.subscriptions.has(topic))
244
+ return;
245
+ this.subscriptions.set(topic, this.subscriptions.get(topic) - 1);
246
+ if (this.subscriptions.get(topic) === 0) {
247
+ this.subscriptions.delete(topic);
248
+ this.mqtt.unsubscribe(topic, (err) => {
249
+ if (err)
250
+ this.mqtt.emit("error", err);
251
+ });
252
+ }
253
+ }
254
+ /* determine RPC error */
255
+ _buildError(payload, error) {
256
+ /* determine error type and build appropriate JSON-RPC error */
257
+ let rpcError;
258
+ switch (typeof error) {
259
+ case "undefined":
260
+ rpcError = new JsonRpcError("undefined error", 0);
261
+ break;
262
+ case "string":
263
+ rpcError = new JsonRpcError(error, -1);
264
+ break;
265
+ case "number":
266
+ case "bigint":
267
+ rpcError = new JsonRpcError("application error", Number(error));
268
+ break;
269
+ case "object":
270
+ if (error === null)
271
+ rpcError = new JsonRpcError("undefined error", 0);
272
+ else {
273
+ if (error instanceof JsonRpcError)
274
+ rpcError = error;
275
+ else if (error instanceof Error)
276
+ rpcError = new JsonRpcError(error.toString(), -100, error);
277
+ else
278
+ rpcError = new JsonRpcError("application error", -100, error);
279
+ }
280
+ break;
281
+ default:
282
+ rpcError = new JsonRpcError("unspecified error", 0, { data: error });
283
+ break;
284
+ }
285
+ return JSONRPC.error(payload.id, rpcError);
286
+ }
287
+ }